Game Development Reference
In-Depth Information
This is much easier than having to type in all the content a variable should have. The expression
new Image()
basically does that work for you. By using types, you now have an easy way to create
objects, and you can be sure these objects always have the same structure. When an object is
constructed that has the structure as dictated by the
Image
type, you say that this object
is of type
Image
.
You didn't yet indicate what
data
should be contained in this variable. You can set the source file of
this image by assigning the file name to the
src
variable that is always part of an
Image
object:
Game.balloonSprite.src = "spr_balloon.png";
Once the
src
variable is set, the browser begins loading the file. The browser automatically fills in the
data for the
width
and
height
variables because it can extract this information from the source file.
Sometimes, loading the source file takes a while. For example, the file could be stored on a web site
on the other side of the world. This means if you try to draw the image immediately after setting its
source file, you may run into trouble. As a result, you need to make sure each image is loaded before
you can start the game. There is a very neat way to do this, by using an
event handler
function. In
Chapter 7, you see how that works. For now, just assume that loading the image will not take longer
than half a second. By using the
setTimeOut
method, you call the
mainLoop
method after a delay of
500 milliseconds:
window.setTimeout(Game.mainLoop, 500);
This completes the
start
method, which now looks like this:
Game.start = function () {
Game.canvas = document.getElementById("myCanvas");
Game.canvasContext = Game.canvas.getContext("2d");
Game.balloonSprite = new Image();
Game.balloonSprite.src = "spr_balloon.png";
window.setTimeout(Game.mainLoop, 500);
};
Sprites can be loaded from any location. If you're developing a game in JavaScript, then it's a good
idea to think about the organization of your sprites. For example, you could put all the sprites belonging
to your game in a subfolder called
sprites
. You would then have to set the source file as follows:
Game.balloonSprite.src = "sprites/spr_balloon.png";
Or perhaps you aren't even using your own images, but you refer to images that you found on
another web site:
Game.balloonSprite.src = "
http://www.somewebsite.com/images/spr_balloon.png
"
;
JavaScript allows you to load image files from any location you desire. Just make sure that when
you load images from another web site, the location of the image files is fixed. Otherwise, if the
administrator of that web site decides to move everything without telling you, your game won't
run anymore.
Search WWH ::
Custom Search