我的代码创建了一个圆形,它会掉落到画布底部并反弹。问题是我需要创建多个这样的圆形。我该怎么做?
var canvas = document.getElementById('mcanvas');
var raf;
function rainDrop() {
this.x = Math.random() * (canvas.width - (canvas.width - canvas.width)) + (canvas.width - canvas.width);
this.y = 0;
this.vx = -0.5;
this.vy = 1;
this.radius = 1;
this.color = 'blue';
this.gravity = 2;
this.gravitySpeed = 0;
this.bounce = 1;
this.ctx = canvas.getContext('2d');
this.draw = function() {
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;
this.ctx.fill();
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.vx;
this.y += this.vy + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = canvas.height - this.radius;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = -(this.gravitySpeed / 1.5 * this.bounce);
}
}
}
var ball = new rainDrop();
function drawf() {
ball.ctx.clearRect(0, 0, canvas.width, canvas.height);
ball.draw();
ball.newPos();
raf = window.requestAnimationFrame(drawf);
}
canvas.addEventListener('mouseover', function(e) {
raf = window.requestAnimationFrame(drawf);
});
ball.draw();
<canvas id="mcanvas" width="200" height="100"></canvas>
我希望代码能够:绘制多个这样的圆形,而无需编写数百行变量。
ball.ctx.clearRect(0,0, canvas.width, canvas.height);
放入一个单独的函数中,只有在您想要删除所有内容时才调用该函数。 - Shilly