html5画布创建随机矩形

时间:2018-06-17 12:26:16

标签: javascript canvas

  1. 为什么会产生类型错误
  2. 花了30分钟发布这个问题我不知道需要多少详细信息才能解决这个问题,因为我不知道我的代码有什么问题我需要帮助 代码从这里开始: -
    var canvas = document.querySelector("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    var ctx = canvas.getContext("2d");
    
    function rectangle(x, y, dx, dy) {
      this.x = x;
      this.y = y;
      this.dx = dx;
      this.dy = dy;
      this.draw = function() {
        ctx.beginPath();
        ctx.rect(this.dx, this.dy, this.x, this.y);
        ctx.fillStyle = "blue";
        ctx.fill();
        ctx.strokeStyle = "green";
        ctx.stroke();
      }
    
      this.dipendu = function() {
        if (this.dx + this.x > innerWidth || this.dx - this.x < 0) {
          this.dx = -this.dx;
        }
        if (this.dy + this.y > innerHeight || this.dy - this.y < 0) {
          this.dy = -this.dy;
        }
        this.x += this.dx;
        this.y += this.dy;
    
        this.draw();
      }
    }
    var rcontainer = [];
    for (var i = 0; i <= 100; i++) {
      var x = Math.random() * innerWidth;
      var y = Math.random() * innerHeight;
      var dx = Math.random() * innerWidth;
      var dy = Math.random() * innerHeight;
      rcontainer.push(new rectangle(x, y, dx, dy));
    }
    
    function animation() {
      requestAnimationFrame(animation);
      ctx.clearRect(0, 0, innerWidth, innerHeight);
    
      for (var j = 0; j <= rcontainer.length; j++) {
        rcontainer.update();
      }
    }
    
    animation();
    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <title>motion</title>
      <style>
        #mycanvas {
          border: 1px solid black;
        }
      </style>
    </head>
    
    <body>
      <canvas id="mycanvas"></canvas>
      <script src="motion.js"></script>
    </body>
    
    </html>

0 个答案:

没有答案