O'Reilly logo

Professional HTML5 Mobile Game Development by Pascal Rettig

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Writing a Sprite-Map Generator

With the logistics of putting together a Node module out of the way, next up is actually making that module useful. The purpose of the module is to generate a sprite map PNG and corresponding JSON given a directory of image files. Sprite maps are useful in HTML5 game development because you don’t want to load hundreds of separate image files to handle animations, but rather, as you’ve seen, load one or a small number of spritesheet files that have multiple images on them.

Follow these steps to achieve the goal of the script:

1. Take a directory of image files in numbered sequences (that is, ship01.png, ship02.png, ..., enemy01.png, enemy02.png, ...).
2. Output a sprite map where each row of images corresponds to a numbered list of files.
3. Output a JSON file detailing the pixel locations and number of frames of each sprite that can be loaded into the game engine that will be built in the next few chapters.

The next sections will put together the pieces for this script.

Using Futures

The way to load images with node-canvas is the same as you might load them on the client side: Set the src property and then wait for an onload event. Because this is an asynchronous event, in theory, images may load out of order (or not load at all) and keeping track of all this requires a bit of housekeeping or a vast amount of nested callbacks.

Luckily, there’s the Promise pattern, which encapsulates the idea of handling future events in a sequential manner. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required