HTML and CSS Reference
In-Depth Information
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
movement 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 would 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
var points = new Array();
Next, we load a black 4×4 pixel image, point.png , that 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:
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:
for (var i = 0; i< points.length; i++) {
context.drawImage(pointImage, points[i].x, points[i].y,1,1);
In Figure 5-1 , you can see what the ball looks like when moving on a line from one
point to another, and also what the points path looks like when it is drawn.
This is the only time in this chapter where we will discuss the points
path in depth. If you see the points being drawn, you will know how
and why we have added that functionality. You should also have enough
information to remove the code when necessary.
Search WWH ::

Custom Search