Canvas实现彩色小球

话不(画布)多说,直接上代码,效果如图,画布尺寸为500px * 500px

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid #444;
        margin: 0 auto;
        display: block;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="500px" height="500px"
      >浏览器版本过低,请升级最新版本谷歌浏览器(只有低版本浏览器才会显示标签内的文字)</canvas
    >
  </body>
  <script>
    //获取canvas画布
    var canvas = document.querySelector('#canvas');
    //获取上下文
    var ctx = canvas.getContext('2d');
    //画布参数
    var w = 500;
    var h = 500;
    var x = 21;
    var y = 21;
    var r = 20;
    var speedX = 2;
    var speedY = 5;

    //获取随机数
    function f(num) {
      return Math.random() * num;
    }
    //第一步:创建小球类
    function Ball() {
      this.x = f(400) + 50;
      this.y = f(400) + 50;
      this.r = f(40) + 10;
      this.color = '#' + parseInt(Math.random() * 0xffffff).toString(16);
      this.speedX = f(3) + 2;
      this.speedY = f(3) + 1;
    }
    //第二步:定义小球显示方法
    Ball.prototype.show = function () {
      this.run();
      drawBall(this.x, this.y, this.r, this.color);
    };
    //第三步:定义小球触壁改向的方法
    Ball.prototype.run = function () {
      if (this.x - this.r <= 0 || this.x + this.r >= w) {
        this.speedX = -this.speedX;
      }
      if (this.y - this.r <= 0 || this.y + this.r >= h) {
        this.speedY = -this.speedY;
      }
      this.x = this.x + this.speedX;
      this.y = this.y + this.speedY;
    };
    //第四步:创建小球并加入小球数组
    var ballArr = [];
    for (var i = 0; i < 50; i++) {
      var ball = new Ball();
      ballArr.push(ball);
      ball.show();
    }
    //第五步:让创建好的小球运动
    setInterval(() => {
      ctx.clearRect(0, 0, w, h);
      for (var i = 0; i < ballArr.length; i++) {
        var ball = ballArr[i];
        //再次调用小球显示方法
        ball.show();
      }
    }, 12);
    //封装显示小球
    function drawBall(circle_x, circle_y, circle_r, color) {
      ctx.beginPath();
      ctx.arc(circle_x, circle_y, circle_r, 0, Math.PI * 2, true);
      ctx.fillStyle = color;
      ctx.fill();
    }
  </script>
</html>

猜你喜欢

转载自blog.csdn.net/Xwf1023/article/details/126755906