forked from csstrick/HTML-CSS-js.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbubble.html
82 lines (77 loc) · 2.28 KB
/
bubble.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
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
<!DOCTYPE html>
<html>
<head>
<title>Bubble Animation</title>
<style>
canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const bubbles = [];
class Bubble {
constructor(x, y) {
this.x = x;
this.y = y;
this.radius = Math.random() * 50 + 10;
this.color = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.5)`;
this.speed = Math.random() * 5 + 1;
this.angle = Math.random() * 360;
this.vx = this.speed * Math.cos(this.angle);
this.vy = this.speed * Math.sin(this.angle);
this.lifetime = 5000;
this.birthtime = Date.now();
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
}
update() {
this.x += this.vx;
this.y += this.vy;
if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
this.vx = -this.vx;
}
if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
this.vy = -this.vy;
}
this.draw();
this.remove();
}
remove() {
if (Date.now() - this.birthtime >= this.lifetime) {
bubbles.splice(bubbles.indexOf(this), 1);
}
}
}
canvas.addEventListener('mousemove', (event) => {
const x = event.clientX;
const y = event.clientY;
for (let i = 0; i < 5; i++) {
bubbles.push(new Bubble(x, y));
}
});
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < bubbles.length; i++) {
bubbles[i].update();
}
}
animate();
</script>
</body>
</html>