HTML and CSS Reference
In-Depth Information
"canvas" : "0.10.2",
"futures": "2.3.1"
},
"bin": "./bin/spriter",
"main": "./spriter.js"
}
The name, description, author, and version fields should be relatively self-explanatory. If you plan to publish
your module to npm, the version field is important as you update you module. The
dependencies
field is a
hash of other modules this module depends on and the versions that should be installed. The
bin
field will be
used later when the module is linked to allow you to call this script from anywhere at the command line. Finally
the
main
parameter indicates which file holds the main script file that handles exports.
bin
and
main
aren't
needed now, but they will be needed in subsequent sections.
This code uses a neat server-side Canvas module that gives you a Canvas 2-D API you can use from server-
side node code. It has a dependency on a pair of graphics libraries called
cairo
and
pixman
that you need to
install. It also uses the futures module, which provides Promises and Deferreds functionality. If you aren't fa-
miliar with Promises or Deferreds, don't worry; they will be touched on later in this chapter.
On Linux you can install either the libcairo2-dev (Debian and Ubuntu) or the cairo-devel (Fedora and
openSUSE) package. On Ubuntu—or if you run the Ubuntu virtual machine—this means running the following
from the command line:
sudo apt-get install libcairo2-dev
On OS X install cairo via Homebrew with the following:
brew install cairo pixman
After you install the cairo library, run the following command from your
spriter
directory to install any
dependencies:
npm install
This downloads and installs the Canvas dependency into the
node_modules
subdirectory, and you should
start building this node script.
Using Server-Side Canvas
The first thing you need to do is test the server-side Canvas functionality to ensure it's usable. Draw the standard
canvas example of two overlapping rectangles.
File I/O is generally done in an asynchronous manner in Node when writing web servers. However, when
writing command-line scripts, you can relax the callback pattern some and use the
Sync
versions of methods
that do their jobs synchronously.
Node provides a method called
fs.writeFilSync
that takes a filename and a buffer and writes the con-
tents of that buffer to the file.
node-canvas
has a method called
canvas.toBuffer()
that can generate
the buffer from the canvas. You can use
canvas.toBuffer()
asynchronously with a callback, but in this
case you can use the synchronous version.
Listing 8-2:
Spriter.js boilerplate