Game Development Reference
In-Depth Information
Drawing Sprites
Loading a sprite and storing it in memory doesn't mean the sprite is drawn on the screen. For that to
happen, you need to do something in the draw method. To draw a sprite on the canvas somewhere,
you use the drawImage method that is a part of the canvas context object. In JavaScript, when an
image is drawn at a certain position, that position always refers to the top-left corner of the image.
Here is the instruction that draws a sprite in the top-left corner on the screen:
Game.canvasContext.drawImage(sprite, 0, 0, sprite.width, sprite.height,
0, 0, sprite.width, sprite.height);
The drawImage method has a number of different parameters. For example, you can indicate at which
position you want to draw the sprite, or whether only a part of the sprite should be drawn. You could
simply call this method and be done with it. However, if you're thinking about future games you want
to build, you can use a drawing state to draw the sprite.
A drawing state basically is a set of parameters and transformations that will be applied to all things
drawn within that state. The advantage of using a drawing state instead of separately calling the
drawImage method is that you can do more complicated transformations with sprites. For example,
with drawing states, you can rotate or scale sprites, which is a very useful feature in games. Creating
a new drawing state is done by calling the save method:
Game.canvasContext.save();
You can then apply a variety of transformations within this drawing state. For example, you can
move (or translate ) the sprite to a certain position:
Game.canvasContext.translate(100, 100);
If you call the drawImage method now, the sprite is drawn at position (100, 100). And once you're
done drawing, you can remove the drawing state as follows:
Game.canvasContext.restore();
For convenience, let's define a method that does all this work for you:
Game.drawImage = function (sprite, position) {
Game.canvasContext.save();
Game.canvasContext.translate(position.x, position.y);
Game.canvasContext.drawImage(sprite, 0, 0, sprite.width, sprite.height,
0, 0, sprite.width, sprite.height);
Game.canvasContext.restore();
};
As you can see by looking at the parameters , this method requires two pieces of information: the
sprite that should be drawn and the position at which it should be drawn. The sprite should be of type
Image (although you can't easily enforce this in JavaScript when you define a function). The position is
an object variable consisting of an x part and a y part. When you call this method, you have to provide
this information. For example, you can draw the balloon sprite at position (100, 100) as follows:
Game.drawImage(Game.balloonSprite, { x : 100, y : 100 });
 
Search WWH ::




Custom Search