HTML and CSS Reference
In-Depth Information
setInterval(drawScreen, 100 );
}
By running this example, we see the tank move slowly up the canvas while its tracks
play through the eight separate tiles of animation.
Our tile sheet only has images of the tank facing in the up position. If we want to have
the tank move in other directions, we can do one of two things. The first option is to
create more tiles on the tile sheet to represent the left, right, and down positions. How-
ever, this method requires much more work and creates a larger source image for the
tile sheet. We are going to solve this problem in another way, which we will examine
next.
Applying Rotation Transformations to an Image
In the previous section, we created an animation using tiles from a tile sheet. In this
section, we will take it one step further and use the Canvas transformation matrix to
rotate our image before drawing it to the canvas. This will allow us to use only a single
set of animated tiles for all four (or more) rotated directions in which we would like to
display our images. Before we write the code, let's examine what it will take to rotate
our tank animation from the previous section.
In Chapter 2 , we dove into applying basic transformations when draw-
ing with paths. The same concepts apply to transforming images on the
canvas. If you have not read the section “Simple Canvas Transforma-
tions” on page 41 in Chapter 2 , you might want to review it before
reading on.
Canvas Transformation Basics
Although we covered basic Canvas transformations in detail in Chapter 2 , let's review
what's necessary to transform an individual object on the canvas. Remember, the can-
vas is a single immediate-mode drawing surface, so any transformations we make are
applied to the entire canvas. In our example, we are drawing two objects. First, we draw
a gray background rectangle, and then we copy the current tile from our tile sheet to
the desired location. These are two discrete objects, but once they are on the canvas,
they are both simply collections of pixels painted on the surface. Unlike Flash or other
platforms that allow many separate sprites or “movie clips” to occupy the physical
space, there is only one such object on Canvas: the context .
To compensate for this, we create logical display objects. Both the background and the
tank are considered separate logical display objects. If we want to draw the tank but
rotate it with a transformation matrix, we must separate the logical drawing operations
by using the save() and restore() Canvas context functions.
Search WWH ::




Custom Search