它的名字是: Canvas Particle

代码和效果预览

最初的想法:

在canvas画出随机的点并计算点之间的距离连线

1
'use strict'
2
3
class Ball {
4
	constructor(x, y, xSpeed, ySpeed) {
5
	    this.x = x;
6
	    this.y = y;
7
	    this.xSpeed = xSpeed;
8
	    this.ySpeed = ySpeed;
9
	 }
10
11
	 draw() {
12
	 	//TODO 画出点
13
	 	//TODO 循环这个点与其他点的距离并连线
14
	 }
15
16
	 update() {
17
	 	this.x += this.xSpeed;
18
		this.y += this.ySpeed;
19
		this.xSpeed *= (this.x >= canvas.width || this.x <= 0) ? -1 : 1;
20
		this.ySpeed *= (this.y >= canvas.height || this.y <= 0) ? -1 : 1;
21
		this.draw();
22
	 }
23
}
24
25
const animate = () => {
26
	requestAnimationFrame(animate);
27
	// TODO
28
}
29
30
animate();

实际效果不理想,太卡了. 可能是因为在循环计算距离时会不停的创建对象(待确认).

修改之后:

1
'use strict'
2
3
let dots = [];
4
for (let i=0; i<200; i++) {
5
	dots.push({
6
		x: Math.random() * canvas.width,
7
		y: Math.random() * canvas.height,
8
		xSpeed: getRandomNumber(),
9
		ySpeed: getRandomNumber(),
10
		max: 6000
11
	});
12
}
13
14
const animate = () => {
15
	requestAnimationFrame(animate);
16
	ctx.clearRect(0, 0, canvas.width, canvas.height);
17
	for (let dot of balls) {
18
		dot.x += dot.xSpeed;
19
		dot.y += dot.ySpeed;
20
		dot.xSpeed *= (dot.x >= canvas.width || dot.x <= 0) ? -1 : 1;
21
		dot.ySpeed *= (dot.y >= canvas.height || dot.y <= 0) ? -1 : 1;
22
		ctx.fillRect(dot.x - 0.5, dot.y - 0.5, 1, 1);
23
		
24
		for (let dot2 of balls) {
25
			//TODO 计算距离并画出连线
26
		}
27
	}
28
}
29
30
animate();

之后改成了Json对象+函数的形式,效果不错.