基于canvas-放射粒子效果

4次阅读

共计 1697 个字符,预计需要花费 5 分钟才能阅读完成。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>html5 粒子放射效果 </title>

    <style>
      body {
        overflow: hidden;
        margin: 0;
        padding: 0;
        background-color: #222222;
      }
    </style>
  </head>

  <body>
    <canvas id="canvasParticle">Canvas is not supported in your brower.</canvas>

    <script>
      window.onload = function() {var oCanvas = document.getElementById("canvasParticle");
        var cxt = null;
        var particles = [];
        var particleIndex = 0;
        var num = 0;

        if (oCanvas.getContext) {cxt = oCanvas.getContext("2d");
        }
        // for (var i = 0; i < 200; i++) {//     var a = new Particle();
        //     particles.push(a);
        // }
        oCanvas.width = window.innerWidth;
        oCanvas.height = window.innerHeight;

        function Particle() {if (num < 200) {
            num++;
            particleIndex++;
          }
          console.log(11111, num);
          particles[particleIndex] = this;
          this.x = window.innerWidth / 2;
          this.y = window.innerHeight / 2;
          this.vx = Math.random() * 6 - 3;
          this.vy = Math.random() * 4 - 2;
          this.growth =
            (Math.abs(this.vx) * Math.random() * 0.5 +
              Math.abs(this.vy) * Math.random()) *
            0.005; // 根据 x / y 轴的位置决定大小
          this.id = particleIndex;
          this.size = 0;
          this.color = getRandomColor();}

        Particle.prototype.draw = function() {
          this.x += this.vx * 0.3;
          this.y += this.vy * 0.3;
          this.size += this.growth;

          if (
            this.x < 0 ||
            this.x > oCanvas.width ||
            this.y < 0 ||
            this.y > oCanvas.height
          ) {delete particles[this.id];
            num--;
            console.log(222, num);
            new Particle();}

          cxt.fillStyle = this.color;
          cxt.beginPath();
          cxt.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
          cxt.fill();};

        function animate() {requestAnimationFrame(animate);
          cxt.fillStyle = "#222222";
          cxt.fillRect(0, 0, oCanvas.width, oCanvas.height);
          new Particle();
          for (var i in particles) {particles[i].draw();}
        }
        requestAnimationFrame(animate);
      };

      function getRandomColor() {var color = "#" + ((Math.random() * 0xffffff) << 0).toString(16);
        // var color1 =
        //   "rgba(255,255," + Math.random() * 150 + "," + Math.random() + ")";
        // console.log(color1);
        return color;
      }
    </script>
  </body>
</html>
正文完
 0