HTML5 Canvas [66]
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 canvas:
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:
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:
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.
NOTE
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.
Figure 5-1. A ball moving from one point to another along the line, with the points drawn for illustration
Example 5-2 is the full code listing for CH5EX2.html.
Example 5-2. Moving on a simple line
Moving on a Vector
Moving between two points is handy, but sometimes you don’t have a point to move to, only a point to start from. In cases like this, it can be very useful to create a vector as a means to move your object.
A vector is a quantity in