尝试动画一些球,这些球在画布上以间隔出现。
球每隔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();
答案 0 :(得分:0)
你需要做两件事 - 首先,更新你的'球'位置。您刚刚执行此操作一次,您需要将其放在setInterval或其他每秒更新几次的方法中。其次,你需要在每次球移动时重绘画布(每次更新一次,而不是每个球一次)。一个例子:
setInterval(function () {
balls.forEach(a=>a.animate());
context.fillStyle = "white";
context.fillRect(0, 0, w, h);
balls.forEach(a=>a.draw());
}, 30);
在for循环后在渲染函数中添加它。