簡體   English   中英

無法為畫布上的球設置動畫

[英]Can't animate balls on canvas

嘗試為一些動畫設置動畫,這些動畫在畫布上以一定間隔出現。

球確實每隔n *秒出現一次,但我無法使它們移動:c

我究竟做錯了什么?

https://jsbin.com/mexofuz/26/edit?js,output

function Ball(){
    this.X = 50;
    this.Y = 50;
    this.radius = Math.floor(Math.random()*(30-10)+10);
    this.color = getRandomColor();
    this.dx = Math.floor(Math.random()*(20-10)+10);
    this.dy = Math.floor(Math.random()*(20-10)+10);
}
Ball.prototype.draw = function(){
    context.fillStyle = this.color;
    context.beginPath();
    context.arc(this.X, this.Y, this.radius, 0, Math.PI*2, true);
    context.closePath();
    context.fill();   
}
Ball.prototype.animate = function(){
  if(this.X<0 || this.X>(w-this.radius)) this.dx=-this.dx; 
  if(this.Y<0 || this.Y>(h-this.radius)) this.dy=-this.dy;
  this.X+=this.dx;
  this.Y+=this.dy;
}

var balls = [];

function render() {
    context.fillStyle = "white";
    context.fillRect(0, 0, w, h);
    for(var i = 1;i<=20;i++){
      balls[i] = new Ball();
      setTimeout(Ball.prototype.draw.bind(this.balls[i]), 5000 * i);
   // Ball.prototype.animate.bind(this.balls[i]);
      if (balls[i].X < 0 || balls[i].X > w-balls[i].radius) {
        balls[i].dx = -balls[i].dx;
      }

      if (balls[i].Y < 0 || balls[i].Y > h-balls[i].radius) {
        balls[i].dy = -balls[i].dy;
      }
        balls[i].x += balls[i].dx
        balls[i].y += balls[i].dy
 }
  console.log(balls);
}
render();

您需要做兩件事-首先,更新您的“球”位置。 現在,您只需執行一次,就需要將其放在setInterval或每秒更新幾次的另一種方法中。 其次,您需要在每次球移動時重新繪制畫布(每次更新一次即可,而不是每個球一次)。 一個例子:

setInterval(function () {
 balls.forEach(a=>a.animate());
 context.fillStyle = "white";
 context.fillRect(0, 0, w, h);
 balls.forEach(a=>a.draw());
}, 30);

在for循環之后,將其添加到渲染函數中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM