HTML and CSS Reference
In-Depth Information
ctx.fillRect(0,0,100,100);
ctx.fillStyle = "#C00";
ctx.fillRect(50,50,100,100);
fs.writeFileSync("./sprites.png",canvas.toBuffer());
}
// Make the spriter method available
module.exports = spriter;
The functionality is now wrapped up in a function that can be called externally.
Next, open a file called
spriter
(no extension) in a
bin
subdirectory of your module, and add the code in
Listing 8-4:
bin/spriter command-line script
#!/usr/bin/env node
var spriter = require('../spriter');
spriter();
The only purpose of this script is to load the module you just wrote and then call the
spriter
function.
You need to make the file executable by flipping on the executable bit. Run the following from the command
line in your
spriter
directory:
chmod a+x bin/spriter
Next, you can use the
npm link
command to make the
bin
file available throughout the system while still
letting you modify the code. From the
spriter
directory, run the following:
npm link
You can now run the
spriter
command from the command line anywhere in the system and have the (ad-
mittedly useless)
sprites.png
file created. In the next section, you turn
spriter
into a useful sprite map
generator.
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 use-
ful. 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
, ...,
en-
emy01.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.