js实现可爱的气泡特效


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

代码:

<!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>

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


相关链接