【代码】炫彩小球效果

前言

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
109
110
111
112
113
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
</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 - 30;
canvas.height = document.documentElement.clientHeight;

// 创建构造函数
function Ball(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
this.color = randomColor();
// 小球移动坐标
this.dx = parseInt(Math.random() * 20) - 10;
this.dy = parseInt(Math.random() * 20) - 10;
// 将这个小球维护到数组中
ballArr.push(this);
}

// 创建随机颜色函数
function randomColor() {
let allType = "0.1.2.3.4.5.6.7.8.9.a.b.c.d.e.f";
let allTypeArr = allType.split(".");
// console.log(allTypeArr);
let color = "#";
for (let i = 0; i < 6; i ++) {
let randomType = parseInt(Math.random() * allTypeArr.length);
// console.log(randomType);
color += allTypeArr[randomType];
}
return color;
}

// 渲染小球
Ball.prototype.render = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
}

// 小球移动
Ball.prototype.update = function() {
this.x += this.dx;
this.y += this.dy;
this.r -= 3;
// 如果小球半径小于0,则从数组中删除
if (this.r < 0) {
this.remove();
// console.log("删除了");
}
}

// 小球从数组中清除
Ball.prototype.remove = function() {
for (let i = 0; i < ballArr.length; i ++) {
if (ballArr[i] == this) {
ballArr.splice(i, 1)
}
}
}

// 设置鼠标监听事件,鼠标表移动过程中创建小球
canvas.addEventListener("mousemove", function(event) {
let e = event || window.event;
new Ball(e.offsetX, e.offsetY, 30);
});

// 维护小球的数组
let ballArr = [];

// 设置定时器进行动画渲染和更新
setInterval(function() {
// console.log(ballArr);

// 清屏
ctx.clearRect(0, 0, canvas.width, canvas.height);

for (let i = 0; i < ballArr.length; i ++) {
// 小球的更新和渲染
ballArr[i].update();
if (ballArr[i]) {
ballArr[i].render();
}
}
}, 60)


// console.log(randomColor());

</script>

完成

参考文献

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