Javascript 在画布上创建多个对象

Javascript 在画布上创建多个对象,javascript,Javascript,我的代码创建了一个落在画布底部并反弹的圆圈。问题是我需要创建多个这样的圆。我该怎么做 var canvas=document.getElementById('mcanvas'); var-raf; 函数雨滴(){ this.x=Math.random()*(canvas.width-(canvas.width-canvas.width))+(canvas.width-canvas.width); 这个。y=0; 这是0.vx=-0.5; 这1.vy=1; 这个半径=1; this.color=

我的代码创建了一个落在画布底部并反弹的圆圈。问题是我需要创建多个这样的圆。我该怎么做

var canvas=document.getElementById('mcanvas');
var-raf;
函数雨滴(){
this.x=Math.random()*(canvas.width-(canvas.width-canvas.width))+(canvas.width-canvas.width);
这个。y=0;
这是0.vx=-0.5;
这1.vy=1;
这个半径=1;
this.color='blue';
这个重力=2;
这个重力速度=0;
这个.弹跳=1;
this.ctx=canvas.getContext('2d');
this.draw=函数(){
this.ctx.beginPath();
this.ctx.arc(this.x,this.y,this.radius,0,Math.PI*2,true);
this.ctx.closePath();
this.ctx.fillStyle=this.color;
这个.ctx.fill();
}
this.newPos=函数(){
this.gravitySpeed+=this.gravity;
this.x+=this.vx;
this.y+=this.vy+this.gravitySpeed;
这个;
}
this.hitbooth=函数(){
var rockbottom=canvas.height-this.radius;
如果(this.y>rockbottom){
y=最低点;
this.gravitySpeed=-(this.gravitySpeed/1.5*this.bounce);
}
}
}
var ball=新雨滴();
函数drawf(){
ball.ctx.clearRect(0,0,canvas.width,canvas.height);
ball.draw();
ball.newPos();
raf=window.requestAnimationFrame(drawf);
}
canvas.addEventListener('mouseover',函数(e){
raf=window.requestAnimationFrame(drawf);
});
ball.draw()

可能有更好的方法,但我使用了一组球,并添加了一个forEach

用150个球填充一个新的球数组

var balls = [];

for(var i=0; i<150; i++)
{
    balls[i] = new rainDrop();
}
我还随机化了球的Y起始位置,因为我认为这就是你想要的

 this.y = Math.random() * (canvas.height - (canvas.height-canvas.height)) + (canvas.height-canvas.height);
var canvas=document.getElementById('mcanvas');
var-raf;
函数雨滴(){
this.x=Math.random()*(canvas.width-(canvas.width canvas.width))+(canvas.width canvas.width);
this.y=Math.random()*(canvas.height-(canvas.height canvas.height))+(canvas.height canvas.height);
这是0.vx=-0.5;
这1.vy=1;
这个半径=1;
this.color='blue';
这个重力=2;
这个重力速度=0;
这个.弹跳=1;
this.ctx=canvas.getContext('2d');
this.draw=函数(){
this.ctx.beginPath();
this.ctx.arc(this.x,this.y,this.radius,0,Math.PI*2,true);
this.ctx.closePath();
this.ctx.fillStyle=this.color;
这个.ctx.fill();
}
this.newPos=函数(){
this.gravitySpeed+=this.gravity;
this.x+=this.vx;
this.y+=this.vy+this.gravitySpeed;
这个;
}
this.hitbooth=函数(){
var rockbottom=canvas.height-this.radius;
如果(this.y>rockbottom){
y=最低点;
this.gravitySpeed=-(this.gravitySpeed/1.5*this.bounce);
}
}
}
var=[];

对于(var i=0;我不是每次绘制雨滴时都会清除画布上下文吗?因此,首先将
ball.ctx.clearRect(0,0,canvas.width,canvas.height);
放在一个单独的函数中,你只在想要移除所有内容时调用该函数。清除画布,绘制所有雨滴,循环。这看起来有点疯狂
 this.y = Math.random() * (canvas.height - (canvas.height-canvas.height)) + (canvas.height-canvas.height);