HTML and CSS Reference
In-Depth Information
The Canvas Stack
The Canvas state can be saved to a stack and retrieved. This is important when we are trans-
forming 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
andscaleoperations.Therefore,ifwekepttheshipatthe 0 , 0 locationandrotateditbyitstop-
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 drawCan-
vas() function. To simplify this example, we will remove the shipState variable and con-
centrate on the static state only. We will be adding in three new variables above the drawCan-
vas() 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.
Example 8-5. Rotating an image
//canvasApp level variables
var rotation = 0 ;
var x = 50 ;
var y = 50 ;
function drawScreen () {
// draw background and text
context . fillStyle = '#000000' ;
context . fillRect ( 0 , 0 , 200 , 200 );
context . fillStyle = '#ffffff' ;
Search WWH ::

Custom Search