HTML and CSS Reference
In-Depth Information
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 canvas 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 rect-
angle, and then we copy the current tile from our tile sheet to the desired location. These are
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 con-
text .
To compensate for this, we create logical display objects. Both the background and the tank
areconsidered separate logical display objects. Ifwewanttodrawthetankbutrotate itwitha
transformation matrix, we must separate the logical drawing operations by using the save()
and restore() Canvas context functions.
Let's look at an example where we rotate the tank 90 degrees, so that it is facing to the right
rather than up.
Step 1: Save the current context to the stack
The save() contextfunctionwilltakethecurrentcontentsofthecanvas(inourcase,thegray
background rectangle) and store it away for “safekeeping”:
context . save ();
After we have transformed the tank, we will replace it with the restore() function call.
Step 2: Reset the transformation matrix to identity
The next step in transforming an object is to clear the transformation matrix by passing it val-
ues that reset it to the identity values:
context . setTransform ( 1 , 0 , 0 , 1 , 0 , 0 )
Step 3: Code the transform algorithm
Each transformation will be slightly different, but usually if you are rotating an object, you
will want to translate the matrix to the center point of that object. Our tank will be positioned
at 50,50 on the canvas, so we will translate it to 66,66. Because our tank is a 32×32 square
tile, we simply add half of 32, or 16, to both the x and y location points:
context . translate ( x + 16 , y + 16 );
Search WWH ::

Custom Search