HTML and CSS Reference
In-Depth Information
canvas
now contains the rendered sprite map, and the
jsonOutput
variable has the sprite data indicating
the position of each sprite, so all that's needed is to write out both files to disk. To convert the
jsonOutput
(which is a JavaScript object) into a string, you can call the built-in
JSON.stringify
method.
If you were writing client-side code, you would need to be careful to wrap all this in closure to prevent
namespace pollution, but because Node gives each file its own scope, this isn't necessary.
Loading Images
Now you can attack the
loadImages
method. It takes in the directory, list of files, and a rows data structure
that it needs to populate with lists of images.
Its job is to go over each file in the list, add it to the appropriate row, create an
Image
object, and then start
the loading of the image, binding the
onload
method to the
Join
object to handle the asynchronous loading
as described previously.
The
loadImages
method uses a regular expression to pull out the name and file number from the filename
Listing 8-7:
The loadImages method
function loadImages(directory,files,rowData) {
var fileRegex = /^(.*?)([0-9]+)\.[a-zA-Z]{3}$/,
join = Join();
for(var i=0;i<files.length;i++) {
(function(file) {
var results = file.match(fileRegex),
img = new Image();
if(results) {
var rowName = results[1],
fileNum = parseInt(results[2],10);
img.onload = join.add();
img.onerror = function() {
util.print("Error loading: " + file + "\n"); process.exit(1);
}
img.src = directory.replace(/\/$/,"") + "/" + file;
rowData[rowName] = rowData[rowName] || [];
rowData[rowName].push([fileNum,img]);
}
})(files[i]);
}
return join;
}