Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Created March 19, 2014 02:25
Show Gist options
  • Save JosePedroDias/9634398 to your computer and use it in GitHub Desktop.
Save JosePedroDias/9634398 to your computer and use it in GitHub Desktop.
generates image using node canvas module on server
// https://github.com/learnboost/node-canvas
// https://github.com/LearnBoost/node-canvas/wiki
// sudo apt-get install libcairo2-dev
// npm install canvas
var http = require('http');
var url = require('url');
var Canvas = require('canvas');
// http://stage.sl.pt:8080/?t=hi%20there
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.rotate(.1);
ctx.fillText(t, 50, 100);
var te = ctx.measureText(t);
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.beginPath();
ctx.lineTo(50, 102);
ctx.lineTo(50 + te.width, 102);
ctx.stroke();
var buf = canvasEl.toBuffer();
res.writeHead(200, {'Content-Type': 'image/png'});
res.end(buf, 'binary');
}).listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment