HTML and CSS Reference
When we run Example 8-4 we will see the player ship in the upper-left corner of the
canvas. The static and thrust states will alternate on each frame.
Applying Transformations to Game Graphics
Our game will probably have many individual logical display objects that need to be
updated on a single frame tick. We can make use of the Canvas stack ( save() and
restore() functions), and use the transformation matrix to ensure the final output
affects only the current object we are working on—not the entire canvas.
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. Since 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. So, 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 the y location to start drawing the player ship
Example 8-5 gives the full code.