HTML and CSS Reference
In-Depth Information
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. You saw an example of this in Chapter 5 during the discussion of Deferreds. Node has a number of
different modules that provide Promise and Deferred objects (similar to those in jQuery.) One of the best ones is
the Futures module, which provides a bunch of types of objects to make your life easier. Because it's usable
on both Node and the browser, it's definitely a module worth getting familiar with.
The spriter script uses the Join module from Futures , which provides a way to easily load a bunch
of asynchronous events and then trigger only when all have completed.
To create a new Join you simply call the following:
var join = Join();
You can add a new Promise to the object by calling the following:
var promiseFunction = join.add();
After you add all the promises to the join, you can call the following:
join.when(function(args) {
/* Triggered when all promises have been called */
For example, the code in Listing 8-5 shows how you could use the Futures module to load two images:
Listing 8-5: An example using join
var join = Join(),
img1 = new Image(),
img2 = new Image();
img1.onload = join.add();
img1.src = "images/image1.png";
img2.onload = join.add();
img2.src = "images/image2/png";
join.when(function() {
// Both images have been loaded
Little bookkeeping needs to be done to track the potentially out-of-order loading of both images. The only
important part is that join.when is called after all the images have been added. Listing 8-5 is essentially the
code, scaled-up to however many images are in the passed-in directory that the spriter script will use.
Working from the Top Down
Now it's time to replace the basic Canvas demo in spriter.js with the actual code to generate a sprite map.
In this case it's probably easiest to work from the top down, starting with the highest-level method for generat-
ing the sprite map and then writing the helper methods necessary to make it work.
Search WWH ::

Custom Search