Skip to content

Instantly share code, notes, and snippets.

@bahmutov
Last active April 30, 2018 12:15
Show Gist options
  • Save bahmutov/ed3b2552ccfb619a1658 to your computer and use it in GitHub Desktop.
Save bahmutov/ed3b2552ccfb619a1658 to your computer and use it in GitHub Desktop.
Rendering graphics using Canvas and Path2D polyfill on node
// node-canvas
var Canvas = require('canvas')
console.log('Canvas is', Canvas)
var nodeCanvas = new Canvas(120, 120)
var ctx = nodeCanvas.getContext('2d')
// canvas-5-polyfill patches CanvasRenderingContext2D.prototype
// lets give it one
global.CanvasRenderingContext2D = {};
global.CanvasRenderingContext2D.prototype = ctx;
require('canvas-5-polyfill')
// square outline
var path1 = new Path2D();
path1.rect(10, 10, 100, 100);
ctx.stroke(path1);
// black square inside
var path2 = new Path2D();
path2.rect(20, 20, 80, 80);
ctx.fill(path2);
// green circle in the center
var path3 = new Path2D();
path3.arc(60, 60, 30, 0, 2 * Math.PI);
ctx.fillStyle = 'green';
ctx.fill(path3);
// canvas to PNG file
var fs = require('fs')
var out = fs.createWriteStream(__dirname + '/canvas.png');
var stream = nodeCanvas.pngStream();
stream.on('data', out.write.bind(out));
stream.on('end', console.log.bind(console, 'saved png'));
@kepeterson
Copy link

Thanks for this, saved me a lot of heartburn

@ahmadnassri
Copy link

ahmadnassri commented Mar 30, 2018

skip modifying globals by using getting the CanvasRenderingContext2D object from canvas itself:

const { CanvasRenderingContext2D, createCanvas } = require('canvas')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment