我正在写一个面向对象风格的 JavaScript 演示——只是为了画一堆在屏幕上移动的球。在这一点上没有什么花哨的,没有碰撞检测或任何东西。认为假设我的 Ball.js 类是好的是安全的。
我的问题是这样的:我应该在哪里调用 ball.draw(context) ?以我设置的方式将球绘制到屏幕上的唯一方法似乎是将调用放在 generateBalls() 中。但这意味着每个球只抽一次。
因此,如果有人能在这里指出我的方式的错误,我真的很感激。这不是家庭作业——只是想更好地处理 javascript 和 canvas。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="ball.js"></script>
<script src="utils.js"></script>
...
<canvas id="canvas" width="600" height="480"></canvas>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}
function canvasSupport() {
return true;
}
function canvasApp() {
if(!canvasSupport()) {
return;
}
}
console.log("app entered");
var numBalls = 45;
//var numBalls = demo.numberofballs.value;
var maxSize = 8;
var minSize = 5;
var maxSpeed = maxSize + 5;
var balls = new Array();
var tempBall;
var tempX;
var tempY;
var tempSpeed;
var tempAngle;
var tempRadius;
var tempRadians;
var tempXunits;
var tempYunits;
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
generateBalls();
setInterval(drawScreen, 33);
function generateBalls() {
console.log("Make some balls");
for(var index = 0; index < numBalls; index++) {
var tempRadius = Math.floor(Math.random()*maxSize)+minSize;
var ball = new Ball(tempRadius, "#000000");
ball.x = tempRadius * 2 + (Math.floor(Math.random()*canvas.width) - tempRadius * 2);
ball.y = tempRadius * 2 + (Math.floor(Math.random()*canvas.height) - tempRadius * 2);
ball.speed = maxSpeed - tempRadius;
ball.angle = Math.floor(Math.random()*360);
ball.dx = Math.cos(tempRadians) * tempSpeed;
ball.dy = Math.sin(tempRadians) * tempSpeed;
// here outputted balls but a stupid place to put it LOL
balls.push(ball);
}
}
function drawScreen() {
console.log("draw screen");
// loop through all balls and adjust their position
// a BallManager could do this more cleanly
for(var index = 0; index < balls.length; index++) {
context.fillStyle="#EE00EE";
context.fillRect(0,0,canvas.width, canvas.height);
// Box
context.strokeStyle = "#ff0043";
context.strokeRect(1,1,canvas.width-2, canvas.height-2);
// place balls
context.fillStyle = "#ff8783";
console.log("ball mover loop in drawscreen");
// no var ball now
ball = balls[index];
ball.x += ball.dx;
ball.y += ball.dy;
ball.draw(context);
//checkBoundaries(balls[index]);
if(ball.x > canvas.width || ball.x < 0) {
ball.angle = 180 - ball.angle;
updateBall(ball);
} else if(ball.y > canvas.height || ball.y < 0) {
ball.angle = 360 - ball.angle;
updateBall(ball);
//ball.draw(context);
}
}
}
//function checkBoundaries(ball) {
//console.log("Check Bounds: " + " " + "ball.x: " + ball.x + " " + //"ball.y: " + ball.y);
//}
function updateBall(ball) {
ball.radians = ball.angle * Math.PI / 180;
ball.dx = Math.cos(ball.radians) * ball.speed;
ball.dy = Math.sin(ball.radians) * ball.speed;
//ball.draw(context);
}
</script>
</body>
</html>
谢谢你的建议,马克