HTML and CSS Reference
In-Depth Information
var fs = require('fs'),
Canvas = require('canvas'),
canvas = new Canvas(200,200),
ctx = canvas.getContext('2d');
ctx.fillStyle = "#CCC";
ctx.fillRect(0,0,100,100);
ctx.fillStyle = "#C00";
ctx.fillRect(50,50,100,100);
fs.writeFileSync("./sprites.png",canvas.toBuffer());
The vast majority of this code is standard Canvas code similar to what you would write in the browser. The
only parts that are different are the initial require statements and the call to write the file out.
Modules that you install via npm are loaded by calling
require("..")
and then assigning the returned
value to a variable for use. The
fs
module is a built-in library that provides basic file system access in Node.
The
canvas
module, which you installed in the last section, provides functionality that mimics the client-
side Canvas object. You can create new Canvas objects by calling the following:
new Canvas(width,height)
In
Listing 8-2
you created a canvas that was 200 pixels by 200 pixels and then retrieved the context object
the same way you would on the client.
Finally, after a few simple drawing calls, the one-line command to write the canvas out to a .png file is called:
fs.writeFileSync("./sprites.png",canvas.toBuffer());
This creates a buffer object and then writes the buffer to the file specified in the first parameter.
To test this, you can run the following:
node ./spriter.js
This should generate a file in the same directory called
sprites.png
with the two overlapping rectangles.
If you run into any errors, double-check that you installed the canvas module correctly.
Creating a Reusable Script
To make the
spriter
script usable both by other modules and from the command line, you need to make a
few changes to the
spriter.js
file and add the necessary
spriter
script to the
bin
directory.
Node provides an object called
exports
that is returned whenever you
require()
a file. If you aren't
returning an object, you can also override what's returned by setting
module.exports
to whatever you want
to return. In the case of
spriter
, you need to expose only a single function that creates sprites in a sprite file.
Listing 8-3:
An exported spriter.js file
var fs = require('fs'),
Canvas = require('canvas');
function spriter() {
var canvas = new Canvas(200,200),
ctx = canvas.getContext('2d');
ctx.fillStyle = "#CCC";