Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS: serve png generated by node-canvas

Tags:

node.js

canvas

I would like to generate and serve a .png file using node-canvas. Using Express, this is what I have done so far:

draw_badge.js

function draw() {
  var Canvas = require('canvas'),
      Image = Canvas.Image,
      canvas = new Canvas(200, 200),
      ctx = canvas.getContext('2d');

  ctx.font = '30px Impact';
  ctx.rotate(0.1);
  ctx.fillText('Awesome!', 50, 100);

  return canvas;
}

module.exports = draw;

badge.js

var express = require('express');
var router = express.Router();
var draw = require('../lib/draw_badge.js');

router.get('/show', function (req, res, next) {
  res.setHeader('Content-Type', 'image/png');
  res.end(draw());
});

module.exports = router;

But when I go to the route in my browser, I don't see any png. My grasp of node is not firm enough to understand what is going on. Can anyone point me to the right direction?

like image 219
Sung Cho Avatar asked Sep 11 '15 07:09

Sung Cho


1 Answers

Try this in badge.js:

var express = require('express');
var router = express.Router();
var draw = require('../lib/draw_badge.js');

router.get('/show', function (req, res, next) {
  res.setHeader('Content-Type', 'image/png');
  draw().pngStream().pipe(res);
});

module.exports = router;

Notice the code draw().pngStream().pipe(res);

It will obtain a PNG stream from your Canvas and will pipe this stream to the response stream. Doing things this way, you don't need to call res.end(), because when your PNG stream will end, so will your response stream be ended.

like image 130
Cristian Smocot Avatar answered Oct 23 '22 01:10

Cristian Smocot