10

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?

mc9
  • 6,121
  • 13
  • 49
  • 87

1 Answers1

20

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.

Cristian Smocot
  • 626
  • 1
  • 5
  • 13