HTML and CSS Reference
In-Depth Information
for (var i = 0; i < numBalls; i++) {
tempRadius = Math.floor(Math.random()*maxSize)+minSize;
tempX = tempRadius*2 + (Math.floor(Math.random()*theCanvas.width)-tempRadius*2);
tempY = tempRadius*2 + (Math.floor(Math.random()*theCanvas.height)-tempRadius*2);
tempSpeed = maxSpeed-tempRadius;
tempAngle = Math.floor(Math.random()*360);
tempRadians = tempAngle * Math.PI/ 180;
tempXunits = Math.cos(tempRadians) * tempSpeed;
tempYunits = Math.sin(tempRadians) * tempSpeed;
tempBall = {x:tempX,y:tempY,radius:tempRadius, speed:tempSpeed, angle:tempAngle,
xunits:tempXunits, yunits:tempYunits}
balls.push(tempBall);
}
Now we need to draw the balls onto the canvas. Inside drawScreen() , the code to draw
the balls should look very familiar because it is essentially the same code we used for
one ball in Example 5-4 . We just need to loop through the balls array to render each
ball object:
for (var i = 0; i <balls.length; i++) {
ball = balls[i];
ball.x += ball.xunits;
ball.y += ball.yunits;
context.beginPath();
context.arc(ball.x,ball.y,ball.radius,0,Math.PI*2,true);
context.closePath();
context.fill();
if (ball.x > theCanvas.width || ball.x < 0 ) {
ball.angle = 180 - ball.angle;
updateBall(ball);
} else if (ball.y > theCanvas.height || ball.y < 0) {
ball.angle = 360 - ball.angle;
updateBall(ball);
}
}
When you load Example 5-5 in your web browser, you will see a bunch of balls all
moving around the screen independently, as shown in Figure 5-6 . For the fun of it, why
not change the numBalls variable to 500 or 1,000? What does the canvas look like then?
Search WWH ::




Custom Search