The Canvas Stack

The Canvas state can be saved to a stack and retrieved. This is important when we are transforming and animating game objects because we want our transformations to affect only the current game object and not the entire canvas. The basic workflow for using the Canvas stack in a game looks like this:

  1. Save the current canvas to the stack.

  2. Transform and draw the game object.

  3. Retrieve the saved canvas from the stack.

As an example, let’s set up a basic rotation for our player ship. We will rotate it by 1 degree on each frame. Because we are currently drawing the player ship in the top-left corner of the canvas, we are going to move it to a new location. We do this because the basic rotation will use the top-left corner of the ship as the registration point: the axis location used for rotation and scale operations. Therefore, if we kept the ship at the 0,0 location and rotated it by its top-left corner, you would not see it half the time because its location would be off the top and left edges of the canvas. Instead, we will place the ship at 50,50.

We will be using the same HTML code as in Example 8-4, changing out only the drawCanvas() function. To simplify this example, we will remove the shipState variable and concentrate on the static state only. We will be adding in three new variables above the drawCanvas() function:

var rotation = 0; - holds the current rotation of the player ship
var x = 50; - holds the x location to start drawing the player ship
var y = 50; - holds ...

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.