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:
The next sections will put together the pieces for this script.
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. ...