Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
generates image using node canvas module on server
// sudo apt-get install libcairo2-dev
// npm install canvas
var http = require('http');
var url = require('url');
var Canvas = require('canvas');
http.createServer(function(req, res) {
if (req.url === '/favicon.ico') {
res.writeHead(200, {'Content-Type': 'image/x-icon'});
return res.end();
var u = url.parse(req.url, true);
console.log(u.pathname, u.query);
var t = u.query.t;
var canvasEl = new Canvas(200, 200);
var ctx = canvasEl.getContext('2d');
ctx.font = '30px Impact';
ctx.fillText(t, 50, 100);
var te = ctx.measureText(t);
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.lineTo(50, 102);
ctx.lineTo(50 + te.width, 102);
var buf = canvasEl.toBuffer();
res.writeHead(200, {'Content-Type': 'image/png'});
res.end(buf, 'binary');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment