我在codepen上的代码有什么问题

时间:2017-07-03 13:12:48

标签: javascript html5-canvas

这似乎是一个简单的问题,但我似乎无法解决它。这是codepen上的链接。 https://codepen.io/OriginalName/pen/mwXbyw?editors=1010(他们不会让我发布整个代码)。

var c = canvas.getContext("2d");

1 个答案:

答案 0 :(得分:1)



canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var c = canvas.getContext("2d");

var circleArray = [];  

function Circle(x, y, dx, dy, radius, color) {
  this.x = x;
  this.y = y;
  this.dx = dx;
  this.dy = dy;
  this.color = color;
  this.radius = radius;

  this.draw = function() {
    c.beginPath();
    c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);

    c.strokeStyle = this.color;
    c.stroke();
  };
  this.update = function() {
    if (this.x + this.radius > innerWidth || this.x - this.radius < 0) {
      this.dx = -this.dx;
    }

    if (this.y + this.radius > innerHeight || this.y - this.radius < 0) {
      this.dy = -this.dy;
    }

    this.x += this.dx;
    this.y += this.dy;
    this.draw();
  };
}
  var circleArray = [];
  for (var i = 0; i < 100; i++) {
    var x = Math.random() * innerWidth;
    var y = Math.random() * innerHeight;
    var dx = (Math.random() ) * 4;
    var dy = (Math.random() ) * 4;
    var radius = 30;
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    var rgb = "rgba(" + r + ", " + g + ", " + b + ", " + 0.9 + ")";
    circleArray.push(new Circle(x, y, dx, dy, radius, rgb));
    circleArray[i].draw();
  }

  function animate() {
    requestAnimationFrame(animate);
    c.clearRect(0, 0, innerWidth, innerHeight);
    for (var i = 0; i < circleArray.length; i++) {
      circleArray[i].update();
    }
  }

animate();
&#13;
  canvas { 
  border: 5px solid black;
  background: silver;
  }
&#13;
<canvas id="canvas" > </canvas>
&#13;
&#13;
&#13;

这是你想要的吗?你在每个圆圈类的创作中都创造了100个新的圆圈。所以它显示错误Maximum call stack size exceeded