node-canvas – render and stream HTML5 canvas using Node.js
You knew with TJ Holowaychuk joining the team, the already crazy amount of Node goodness from the bright folks over at LearnBoost would only get better.
Today, they’re taking the wraps off of Node Canvas, a server-side implementation of the HTML5 <canvas>
. Node Canvas uses the Cairo library to render Canvas objects and then streams them back to the browser as PNGs.
Like all things Node these days, install using npm
npm install canvas
You can then create Canvas objects with the familiar API.
/**
* Module dependencies.
*/
var Canvas = require('canvas')
, canvas = new Canvas(150, 150)
, ctx = canvas.getContext('2d')
, fs = require('fs');
ctx.fillRect(0,0,150,150); // Draw a rectangle with default settings
ctx.save(); // Save the default state
ctx.fillStyle = '#09F' // Make changes to the settings
ctx.fillRect(15,15,120,120); // Draw a rectangle with new settings
ctx.save(); // Save the current state
ctx.fillStyle = '#FFF' // Make changes to the settings
ctx.globalAlpha = 0.5;
ctx.fillRect(30,30,90,90); // Draw a rectangle with new settings
ctx.restore(); // Restore previous state
ctx.fillRect(45,45,60,60); // Draw a rectangle with restored settings
ctx.restore(); // Restore original state
ctx.fillRect(60,60,30,30); // Draw a rectangle with restored settings
Now the whole point is to stream it back to the browser:
var out = fs.createWriteStream(__dirname + '/state.png')
, stream = canvas.createPNGStream();
stream.on('data', function(chunk){
out.write(chunk);
});
There are great examples in the test suite as well as a side-by-side comparison of Flot vs. node-canvas.
Be sure and catch TJ’s introductory screencast.
LearnBoost is the company behind Socket.io. Be sure and catch Episode 0.3.1 on Websockets if you missed it.
Discussion
Sign in or Join to comment or subscribe