Loading the SpriteSheet

You have already seen most of the code necessary to load a sprite sheet and display sprites on the page. All that remains is to extract the functionality into a package. One enhancement puts in a map of sprite names to their locations to make it easier to draw the sprites on the screen. A second enhancement encapsulates the onload callback functionality to hide the details from any calling classes.

Listing 1-5 shows the entire class.

Listing 1-5: The SpriteSheet class

var SpriteSheet = new function() {
  this.map = { }; 
  this.load = function(spriteData,callback) { 
    this.map = spriteData;
    this.image = new Image();
    this.image.onload = callback;
    this.image.src = 'images/sprites.png';
  };
  this.draw = function(ctx,sprite,x,y,frame) {
    var s = this.map[sprite];
    if(!frame) frame = 0;
    ctx.drawImage(this.image,
                     s.sx + frame * s.w, 
                     s.sy, 
                     s.w, s.h, 
                     x,   y, 
                     s.w, s.h);
  };
}

Although the class is short and has only two methods, it does have a number of things to note. First, because there can be only one SpriteSheet object, the object is created with

new function() { ... }

This puts the constructor function and the new operator on the same line, ensuring that only one instance of this class is ever created.

Next, two parameters pass into the constructor. The first parameter, spriteData, passes in sprite data linking 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 ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.