HTML and CSS Reference
In-Depth Information
Next, two parameters pass into the constructor. The first parameter, spriteData , passes in sprite data link-
ing the rectangles of sprites to names. The second parameter, callback , passes as a callback to the image
onload method.
The second method, draw , is the main workhorse of the class because it does the actual drawing of
sprites onto a context. It takes as parameters the context, the string specifying the name of a sprite from the
spriteData map, an x and y location to draw the sprite, and an optional frame for sprites with multiple
frames.
The draw method uses those parameters to look up the spriteData in the map to get the source location
of the sprite as well as the width and height. (For this simple SpriteSheet class, every frame of the sprite is
expected to be the same size and on the same line.) It uses that information to figure out the parameters to the
more complicated drawImage method, discussed in the “Drawing Images” section earlier in this chapter.
Although this code is designed to be a one-off and only useful for this specific game, you still need to separ-
ate the game data, such as the sprite data and levels, from the game engine to make it easier to test and build in
pieces.
Add in the SpriteSheet to the top of a new file called engine.js file and replace the startGame
function in game.js with the following code:
function startGame() {
SpriteSheet.load({
ship: { sx: 0, sy: 0, w: 18, h: 35, frames: 3 }
},function() {
SpriteSheet.draw(ctx,"ship",0,0);
SpriteSheet.draw(ctx,"ship",100,50);
SpriteSheet.draw(ctx,"ship",150,100,1);
});
}
Here the StartGame function calls SpriteSheet.load and passes in the details for a couple of sprites.
Next, in the callback function (after the images/sprites.png file loads) to test out the drawing function,
it draws three sprites on the canvas.
Modify the bottom of your index.html file to load engine.js first and then game.js :
<body>
<div id='container'>
<canvas id='game' width='480' height='600'></canvas>
</div>
<script src='engine.js'></script>
<script src='game.js'></script>
</body>
Check out sprite_sheet/index.html in the chapter code for the preceding example in a working
form.
Now that the game can draw sprites on the page, you can set up the main game object to orchestrate
everything else.
 
Search WWH ::




Custom Search