乱蹦的小球
2021-09-26 22:17:23 小于 1 分钟
<!DOCTYPE html>
<html lang="en">
<head>
<title>乱蹦的小球</title>
<style type="text/css">
.box {
width: 300px;
height: 300px;
margin: 0 auto;
}
#canvas {
background: #ccc;
}
</style>
</head>
<body>
<div class="box">
<canvas width="300" height="300" id="canvas">您的浏览器不支持canvas请更换浏览器</canvas>
</div>
<script>
var x = 0,
y = 0,
dx = 3,
dy = 5,
canvas //小球从(0,0) 开始移动, 横向步长为3, 纵向步长为 5
var draw = function() {
drawDisc(x, y) // 使用自定义的画圆方法, 在当前(x,y) 坐标出画一个实心圆 // 判断边界值, 调整dx/dy 以改变x/y坐标变化方向
if (x + dy > canvas.width || x + dx < 0) dx = -dx
if (y + dy > canvas.height || y + dy < 0) dy = -dy
x += dx
y += dy
} // 画实心圆函数; 以鼠标当前位置为原点绘制一个蓝色实心圆
var drawDisc = function(x, y) {
var ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, canvas.width, canvas.height) // 清除整个canvas画面
ctx.fillStyle = '#00f'
ctx.strokeStyle = 'f00'
ctx.lineWidth = 3
ctx.beginPath()
ctx.arc(x, y, 20, 0, Math.PI * 2, true) //画圆弧(x坐标, y坐标, 半径, 起始角, 结束角, true[逆时针]| false[顺时针])
ctx.stroke() //描边
ctx.fill() // 填充
ctx.closePath()
}
canvas = document.getElementById('canvas')
setInterval(draw, 10) // 设置绘圆周期为 10 毫秒
</script>
</body>
</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
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