HTML and CSS Reference
In-Depth Information
bottom ( ball.y > theCanvas.height ) of the canvas, we calculate the angle of reflection as
360 degrees minus the angle of the vector on which the ball is traveling:
iif ( ball . x > theCanvas . width || ball . x < 0 ) {
angle = 180 - angle ;
updateBall ();
} else
else iif ( 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-6 illustrates the code.
Example 5-4. Ball bounce
<!doctype html>
<html
<html lang= "en" >
<head>
<head>
<meta
<meta charset= "UTF-8" >
<title>
<title> CH5EX4: Ball Bounce </title>
</title>
< script src = "modernizr.js" >< /script>
< script type = "text/javascript" >
window . addEventListener ( 'load' , eventWindowLoaded , false
false );
function
function eventWindowLoaded () {
canvasApp ();
}
function
function canvasSupport () {
return
return Modernizr . canvas ;
} function
function canvasApp () {
iif ( ! canvasSupport ()) {
return
return ;
}
function
function drawScreen () {
context . fillStyle = '#EEEEEE' ;
context . fillRect ( 0 , 0 , theCanvas . width , theCanvas . height );
//Box
context . strokeStyle = '#000000' ;
context . strokeRect ( 1 , 1 , theCanvas . width - 2 , theCanvas . height - 2 );
ball . x += xunits ;
ball . y += yunits ;
context . fillStyle = "#000000" ;
context . beginPath ();
context . arc ( ball . x , ball . y , 15 , 0 , Math . PI * 2 , true
true );
Search WWH ::




Custom Search