js实现可爱的气泡特效

时间:2022-05-11 20:59:30

本文实例为大家分享了js实现可爱的气泡特效的具体代码,供大家参考,具体内容如下

js实现可爱的气泡特效

代码:

?
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
<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
 
<body>
  <canvas id="myCanvas"></canvas>
  <script>
    var c = document.getElementById("myCanvas");
    c.width = 300;
    c.height = 500;
    var ctx = c.getContext('2d');
 
    var arr = []
 
    function sui() {
      var r = Math.floor(Math.random() * 6 + 5);
      var x = Math.floor(Math.random() * (c.width - 2 * r)) + r;
      var y = c.height - r;
      var opacity = Math.random();
      var red = Math.floor(Math.random() * 256);
      var green = Math.floor(Math.random() * 256);
      var blue = Math.floor(Math.random() * 256);
      var deg = 0;
      var scale = Math.floor(Math.random() * 6 + 10);
      arr.push({
        x,
        y,
        r,
        red,
        green,
        blue,
        opacity,
        deg,
        scale
      })
    }
    setInterval(sui, 40);
    // 再实现变大和绘制
    function dan() {
      ctx.clearRect(0, 0, c.width, c.height);
      arr.forEach((item, i) => {
        item.deg += 0.5;
        item.y -= item.deg;
        item.x += Math.sin(item.deg) * item.scale;
        if (item.y <= item.r) {
          arr.splice(i, 1);
        } else {
          ctx.beginPath();
          ctx.arc(item.x, item.y, item.r, 0, Math.PI * 2);
          ctx.fillStyle = `rgba(${item.red},${item.green},${item.blue},${item.opacity})`;
          ctx.fill();
        }
      })
    }
    setInterval(dan, 100);
  </script>
</body>
 
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/jvhbi/article/details/108354425