-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.匀速运动的小球.html
75 lines (67 loc) · 1.78 KB
/
5.匀速运动的小球.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>匀速运动的小球</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
#canvas {
background-color: beige;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
const ctx = canvas.getContext('2d') // 在2d上下文中绘制
class Ball {
constructor(r = 30, color = 'red', g = 0.1) {
this.r = r
this.color = color
this.timer = null
this.x = 0
this.y = 0
}
draw(ctx) {
const { x, y, color, r } = this
ctx.save()
ctx.beginPath()
ctx.fillStyle = color
ctx.arc(x, y, r, 0, Math.PI * 2)
ctx.fill()
ctx.restore()
}
}
const ball = new Ball()
ball.x = 500
ball.y = 150
ball.draw(ctx)
const v = 0.2
let time = Date.now()
let y = ball.y
!(function render() {
const now = Date.now()
const diff = now - time
time = now
/**
* @设置一个初始时间,在渲染时,每次获取当前时间,计算时间差 => 表明渲染函数每次执行的间隔时间
* @同时更新旧的时间
* @对于计算的时间差 => 让初始速度 * 这个时间差 即为匀速运动
* */
ctx.clearRect(0, 0, canvas.width, canvas.height)
ball.y += v * diff
console.log('diff: ', ball.y - y)
ball.draw(ctx)
y = ball.y
requestAnimationFrame(render)
})()
</script>
</body>
</html>