Canvas 学习3 (星星移动)

星星移动

 1     /** @type {HTMLCanvasElement} */
 2       var canvas = document.getElementById("tutorial");
 3       var ctx = canvas.getContext("2d"); //获得画笔
 4       //设置canvas的宽高为可视宽高
 5       canvas.width = document.documentElement.clientWidth;
 6       canvas.height = document.documentElement.clientHeight;
 7       //画一个星星 ---- 白色实心圆点
 8       // 随机XY坐标
 9       var x = parseInt(Math.random() * canvas.width);
10       var y = parseInt(Math.random() * canvas.height);
11       //设置星星的速度  随机速度  最小速度1
12 
13       var speed_x =
14         1 +
15         parseInt(Math.random() * 3) *
16           Math.pow(-1, parseInt(Math.random() * 10));
17       var speed_y =
18         1 +
19         parseInt(Math.random() * 3) *
20           Math.pow(-1, parseInt(Math.random() * 10));
21 
22       /*
23         让星星随机移动 ---- (改变星星的圆心坐标)
24         重新绘制圆
25       */
26       setInterval(() => {
27         //先清除之前绘制的星星   当前页面可视框内的所有星星
28         ctx.clearRect(0, 0, canvas.width, canvas.height);
29 
30         x += speed_x;
31         y += speed_y;
32         //边界判断
33         speed_x = x < 0 || x > canvas.width ? -speed_x : speed_x;
34         speed_y = y < 0 || y > canvas.height ? -speed_y : speed_y;
35         //重新绘制星星
36         circle(x, y);
37       }, 100);
38 
39       //设置填充色
40       ctx.fillStyle = "#fff";
41       circle(x, y);
42       // 画圆封装成函数
43       function circle(x, y) {
44         var r = 1;
45         //画圆
46         ctx.beginPath();
47         ctx.arc(x, y, r, Math.PI * 2);
48         ctx.closePath();
49         ctx.fill();
50       }

效果:

原文地址:https://www.cnblogs.com/qjh0208/p/13814464.html