-
Notifications
You must be signed in to change notification settings - Fork 3
/
bubblesAnimate.html
79 lines (79 loc) · 3.34 KB
/
bubblesAnimate.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>一个气泡动画</title>
</head>
<body>
<canvas id="test-canvas" style='background: rgba(57,176,248,1);'></canvas>
<script>
class BubbleAnimate {
constructor(canvas, number=20,radius=6,color=[255,255,255],speed=0.2,speedRandomPercent=0.5,startFull=true) {
try{
this.canvas = canvas;
}catch{
throw("please provide canvas dom");
return ;
}
this.ctx = canvas.getContext('2d');
this.width=canvas.width;
this.height=canvas.height;
this.radius=radius;
this.color=color;
this.speed=speed;
this.bubbles = [];
this.speedRandomPercent=speedRandomPercent;
this.startFull=startFull;
for(let i=0; i<number;i++) {
this.bubbles.push({
isReborn:true,
speed: speed+(Math.random()*2-1)*speedRandomPercent*speed,
});
}
this.renderCanvas();
};
renderCanvas() {
this.ctx.clearRect(0,0,this.width,this.height);
this.renderBubbles();
window.requestAnimationFrame(() => this.renderCanvas());
};
renderBubbles() {
//气泡
let initPoint = [this.width/2,this.height];
for(let i = 0;i<this.bubbles.length;i++) {
let bubble = this.bubbles[i];
if(bubble.isReborn) {
let x = (Math.random()-0.5)*this.width*0.96 + initPoint[0];
//气泡半径在一定范围内随机生成
let bubbleRadius = this.radius+ Math.floor(Math.random()*2-1)*0.5;
//判断气泡初始化时是否铺满
let y = this.startFull?this.height*Math.random():(initPoint[1] - bubbleRadius);
bubble.radius = bubbleRadius;
bubble.currentLocation = [x, y];
let opacity = 0.2 + 0.4* Math.random();
bubble.color = `rgba(${this.color[0]}, ${this.color[1]},${this.color[2]}, ${opacity})`;
bubble.isReborn = false;
}else {
this.renderBubble(bubble);
if(bubble.currentLocation[1]<= bubble.radius){
bubble.isReborn = true;
}
bubble.currentLocation[1] = bubble.currentLocation[1] -bubble.speed;
}
}
}
renderBubble(item) {
this.ctx.beginPath();
this.ctx.arc(...item.currentLocation, item.radius, 0, 2*Math.PI);
this.ctx.fillStyle = item.color;
this.ctx.fill();
}
}
let canvas = document.getElementById('test-canvas');
let bubbleCreater= new BubbleAnimate(canvas);
bubbleCreater.renderCanvas();
</script>
</body>
</html>