【代码】小球连线效果

前言

Canvas实现小球连线效果

源代码

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}

canvas {
display: block;
}
</style>
</head>
<body>
<canvas></canvas>
</body>
</html>
<script>

let canvas = document.querySelector("canvas");
console.log(canvas);
let ctx = canvas.getContext("2d");

canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;

function Ball() {
this.x = parseInt(Math.random() * canvas.width) - 10;
this.y = parseInt(Math.random() * canvas.height) - 10;
this.r = 10;
this.color = "gray";
this.dx = parseInt(Math.random() * 10) - 5;
this.dy = parseInt(Math.random() * 10) - 5;

ballArr.push(this);

// 自己在数组中的位置
this.index = ballArr.length - 1;
}

// 小球渲染
Ball.prototype.render = function() {
ctx.beginPath();
// 透明度,1表示实心
ctx.globalAlpha = 1;
// 容错
if (this.x < 5) {
this.x += 5;
}
if (this.y < 10) {
this.y += 10;
}
// 画小球
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();

// 画线
for (let i = this.index; i < ballArr.length; i++) {
if (Math.abs(ballArr[i].x - this.x) < 150 && Math.abs(ballArr[i].y - this.y) < 150) {
ctx.strokeStyle = "gray";
ctx.beginPath();
// 线的透明度
ctx.globalAlpha = 10 / Math.sqrt(Math.pow(ballArr[i].x - this.x, 2) + Math.pow(ballArr[i].y - this.y, 2));
ctx.moveTo(this.x, this.y);
ctx.lineTo(ballArr[i].x, ballArr[i].y);
ctx.closePath();
ctx.stroke();
}
}
}

// 小球更新
Ball.prototype.update = function() {
this.x += this.dx;
this.y += this.dy;

// 当小球出界,反弹
if (this.x < this.r || this.x > canvas.width - this.r) {
this.dx *= -1;
}
if (this.y < this.r || this.y > canvas.height - this.r) {
this.dy *= -1;
}
}

let ballArr = [];

// 创建20个小球
for (let i = 0; i < 20; i ++) {
new Ball();
}

setInterval(function() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < ballArr.length; i++) {
ballArr[i].update();
ballArr[i].render();
}
}, 20);



</script>

完成

参考文献

哔哩哔哩——web前端小清风