HTML and CSS Reference
In-Depth Information
function updateBall() {
radians = angle * Math.PI/ 180;
xunits = Math.cos(radians) * speed;
yunits = Math.sin(radians) * speed;
}
In drawScreen() , we update the position of the ball, and then draw it on the canvas:
ball.x += xunits;
ball.y += yunits;
context.fillStyle = "#000000";
context.beginPath();
context.arc(ball.x,ball.y,15,0,Math.PI*2,true);
context.closePath();
context.fill();
Next, we test to see whether the ball has hit a wall before we draw it to the canvas. If
the ball hits the right side ( ball.x > the Canvas.width ) or the left side of the canvas
( ball.x < 0 ), we set the angle to 180 degrees minus the angle of the vector on which
the ball is traveling. This gives us the angle of reflection. Alternatively, if the ball hits
the top ( ball.y < 0 ) or bottom ( ball.y > theCanvas.height ) of the canvas, we calculate
the angle of reflection with 360 degrees minus the angle of the vector on which the ball
is traveling:
if (ball.x > theCanvas.width || ball.x < 0 ) {
angle = 180 - angle;
updateBall();
} else if (ball.y > theCanvas.height || ball.y < 0) {
angle = 360 - angle;
updateBall();
}
That's it. Example 5-4 demonstrates a ball that bounces off walls using the rules of
physics. Figure 5-5 illustrates the code.
Example 5-4. Ball bounce
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH5EX4: Ball Bounce</title>
<script src="modernizr-1.6.min.js"></script>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}
function canvasSupport () {
return Modernizr.canvas;
}
Search WWH ::




Custom Search