HTML and CSS Reference
In-Depth Information
From a high-level perspective, the spriter needs to load a directory full of images and sort the images
into rows by the filenames. Then spriter needs to calculate the size of the Canvas it needs to create based on
the width of each sprite and the number of images per row and the height of each row. The spriter assumes
that each image in each row will be the same size. (This is a requirement of the game engine, so it's not an
unreasonable assumption.) You then need to actually draw each of the images to canvas and generate the JSON.
Finally the sprites.png and sprites.json files need to be generated.
To start, rewrite the spriter method. Open spriter.js and replace all the code there with the code in
Listing 8-6 .
Listing 8-6: Rewritten spriter method
function spriter(directory) {
var files = fs.readdirSync(directory),
rowData = {},
// Load all the images
join = loadImages(directory,files,rowData);
// Wait for the all images to load
join.when(function() {
// Get the dimensions of the output sprite map
var dimensions = calculateSize(rowData),
canvas = new Canvas(dimensions.width, dimensions.height);
// Draw the images to the canvas and return the JSON data
var jsonOutput = drawImages(rowData,canvas);
// Write out both the sprites.png and sprites.json files
util.print("Wrote sprites.png and sprites.json\n");
// Make the spriter method available
module.exports = spriter;
Now break down the preceding code. The top of the file now contains a few more Node modules that need
to get pulled in, including the aforementioned futures module. The code also pulls out some objects to top-
level variables ( Canvas.Image and Futures.join ) from existing modules for easier access.
Next the spriter function takes a directory name that will be passed in from the bin/spriter script.
It loads all the files in that directory with a quick call to fs.readdirSync . Those files are then passed to
the as-of-yet-unwritten loadImages method, which returns a join that triggers when all the images have
loaded. loadImages also fills in the rows object, which is an object that matches sprite names to the list of
sprite images that make up that row.
Next, after the join.when callback is triggered, the total dimensions of the Canvas are calculated from the
rows of images and a canvas object of that size is created by calling an also yet-to-be-written method called
calculateSize . Finally, the actual drawing to the Canvas is done by the last method that you need to write:
drawImages .
Search WWH ::

Custom Search