Bouncing a Single Ball

In this first example, we will create a ball traveling on a vector. We will set the speed (magnitude) to 5 and the angle (direction) to 35 degrees. The rest of the variables are identical to those in Example 5-3. We are still moving on a vector, but now we will test to see whether the ball hits a “wall” (the edges of the canvas), in which case it will bounce off, using the rule of the angle of reflection. One big change from the previous vector example is the location in which we initialize the values for radians, xunits, and yunits. Instead of setting them up when we initialize the application in canvasApp(), we save that for a call to a new function named updateBall():

var speed = 5;
var p1 = {x:20,y:20};
var angle = 35;
var radians = 0;
var xunits = 0;
var yunits = 0;
var ball = {x:p1.x, y:p1.y};
updateBall();

The updateBall() function is called every time we set a new angle for the ball, because we need to recalculate the radians and find new values for xunits and yunits. A new angle value is generated when the app starts, as well as every time the ball bounces off a wall:

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, ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.