HTML and CSS Reference
In-Depth Information
img.src = 'images/sprites.png';
The image has now shrunk down to the size of the extra parameters that you passed in which are the destin-
ation width and height. This is a second form of drawImage that enables you to scale images up or down to
any dimensions.
The last form of drawImage , however, is the one that you'll use the most often with bitmapped games. It is
also the most complicated and takes a total of nine parameters:
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
This form enables you to specify a source rectangle in the image using parameters sx , sy , sWidth , and
sHeight and a destination rectangle on the canvas using parameters dx , dy , dWidth , and dHeight . As
you've probably figured out, to pull out an individual frame from one of the sprites in the sprite sheet, this is the
format you want to use. Now give it a shot by changing the call to drawImage to:
var img = new Image();
img.onload = function() {
img.src = 'images/sprites.png';
If you reload the page, you see there's now a single instance of the player ship on the canvas. So far so good.
In the next section, you start to build out the structure for an actual game.
Immediate Versus Retained Mode
Canvas is a tool for creating games in what's commonly referred to as Immediate mode . When you use canvas,
all you are doing is drawing pixels onto the page. Canvas doesn't know anything about your spaceships or mis-
siles that fly around. All it cares about are pixels, and most canvas games clear the canvas completely between
frames and redraw everything at an updated position.
Contrast this with using the DOM to create a game. Using the DOM would be equivalent to creating a game in
Retained mode, as the browser keeps track of the “scene graph” for you. This scene graph keeps track of the pos-
ition and hierarchy of objects. Instead of starting from scratch in each frame, you need to adjust only the elements
that have changed and the browser takes care of rendering everything correctly. Which is better? Well, it depends
on your game. See the discussion in Chapter 12, “Building Games in CSS3,” to learn when to use which method.
Creating Your Game's Structure
The code built so far has been a good way to exercise the canvas capabilities you'll be using, but it will need to
be reorganized to turn it into a useful structure for a game. Now take a step back to look at some of the patterns
you want to use putting together the game.
Building Object-Oriented JavaScript
JavaScript is an object-oriented (OO) language. As such, most elements in JavaScript are objects including
strings, arrays, functions and, well, objects are objects in the OO sense.
Search WWH ::

Custom Search