-3
以前沒有真正使用過array
,我想我在這裏犯了一個錯誤 這段代碼產生了隨機顏色/ vx等的第一個球,但沒有其他的球, 我不是確定哪個部分不正確。在陣列js中產生多個球
在animFrame()
函數中出現ball.x += ball.vx
錯誤。
幫助?
var canvas;
var ctx;
var ball;
var numBalls = 5;
function Ball(radius, color) {
this.x = 0;
this.y = 0;
this.vx = 0;
this.vy = 0;
this.radius = radius;
this.color = random_color();
}
Ball.prototype.draw = function (ctx) {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI, true);
ctx.closePath();
ctx.fill();
};
function random_color() {
var letter = "ABCDEF".split("");
var color = "#";
for(var i = 0; i < 6; i++){
color += letter[Math.round(Math.random()*15)];
}
return color;
}
function init() {
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
balls = new Array();
for (var i = 0; i<numBalls; i++){
ball = new Ball(Math.random() * 40 + 5, Math.random() * 0xffffff);
ball.x = Math.random() * canvas.width/2;
ball.y = Math.random() * canvas.height/2;
ball.vx = Math.random() * 6 - 3;
ball.vy = Math.random() * 6 - 3;
ball.draw(ctx);
balls.push(ball)
animFrame();
}
function animFrame() {
requestAnimationFrame(animFrame, canvas);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for(var i = 0; i < numBalls; i++){
var ball = balls[i];
ball.x += ball.vx; // Undefined here down.
ball.y += ball.vy;
if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0)
ball.vx = -ball.vx;
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0)
ball.vy = -ball.vy;
ball.draw(ctx);
}
}
}