Skip to content

Instantly share code, notes, and snippets.

@shancarter
Last active November 7, 2016 19:29
Show Gist options
  • Save shancarter/f877b05acb3bafb9d5844f2342344385 to your computer and use it in GitHub Desktop.
Save shancarter/f877b05acb3bafb9d5844f2342344385 to your computer and use it in GitHub Desktop.
Using d3 to generate canvas png in node.js

In order to generate a raster image with d3 in node.js, you need a canvas context. This is a bare bones example of using a node-based canvas for said context.

#!/usr/bin/env node
var fs = require("fs"),
path = require("path"),
d3 = require("d3"),
Canvas = require("canvas");
var width = 1000,
height = 500;
var canvas = new Canvas(width, height),
context = canvas.getContext("2d");
context.strokeStyle = "rgba(100,0,0,0.5)";
context.beginPath();
context.moveTo(50, height / 2);
context.lineTo(width - 50, height / 2);
context.stroke();
canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, "canvas.png")));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment