mc9
mc9

Reputation: 6349

NodeJS: serve png generated by node-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?

Upvotes: 10

Views: 8933

Answers (1)

Cristian Smocot
Cristian Smocot

Reputation: 666

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.

Upvotes: 20

Related Questions