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 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.
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()
context function
will take the current contents of the canvas (in our case, the gray
background rectangle) and store it away for “safekeeping”:
context
.
save
();
After we have transformed the tank, we will replace it with the
restore()
function ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.