37
ball.x += xunits;
ball.y += yunits;
}
Now that our values have been updated, we simply draw the ball at the x and y coordi‐
nates specified by the x and y properties, and we are done—that is, until drawScreen()
is called 33 milliseconds later:
context.fillStyle = "#000000";
context.beginPath();
context.arc(ball.x,ball.y,15,0,Math.PI*2,true);
context.closePath();
context.fill();
Let’s try the example by executing it in a web browser. You can find it in the code
distribution as CH5EX2.html, or you can type in Example 5-2. Watch the ball move
from one point to another. If you update the x and y values of each point, or change the
speed, watch the results. You can do a lot with this very simple example.
Tracing movement: A path of points
For many of the examples in this chapter, we will create a way to trace an object’s move‐
ment on the canvas by drawing points to show its path. We have done this to help
illustrate how objects move. However, in the real world, you would need to remove this
functionality so that your application will perform to its potential. This is the only place
we will discuss this code, so if you see it listed in any of the later examples in this chapter,
refer back to this section to refresh your memory on its functionality.
First, we create an array in canvasApp() to hold the set of points we will draw on the
canvas:
var points = new Array();
Next, we load a black 4×4 pixel image, point.png, which we will use to display the points
on the canvas:
var pointImage = new Image();
pointImage.src = "point.png";
Whenever we calculate a point for an object we will move, we push that point into the
points array:
points.push({x:ball.x,y:ball.y});
On each call to drawScreen(), we draw the set of points we have put into the points
array. Remember, we have to redraw every point each time because the canvas is an
immediate-mode display surface that does not retain any information about the images
drawn onto it:
196 | Chapter 5: Math, Physics, and Animation