Skip to content

'TypeError: Image or Canvas expected' when importing node-canvas in different modules #487

Open
@automata

Description

@automata

As previously reported at #338 (comment), when someone tries to use canvas on two different modules, it breaks.

For example, if in one module we have:

var Canvas = require('canvas')
  , Image = Canvas.Image
  , other = require('other')
  , temporary = require('temporary')
  , request = require('request')
  , fs = require('fs'),
  , url = 'http://foo.com/bar.jpg',
  , tmpFile = new temporary.File(),
  , stream = fs.createWriteStream(tmpFile.path),
  , req = request({url: url, timeout: 10000});

req.pipe(stream);

req.on('response', function (resp) {
  if (resp.statusCode === 200) {
    return;
  }
});

req.on('end', function () {
  loadFile(tmpFile.path);
});

var loadFile = function (path) {
  fs.readFile(path, function (err, image) {
    var img = new Image();
    img.onload = function () {
      other.draw(img);
    }
    img.src = image;
  });
};

And in the other:

var Canvas = require('canvas')
  , Image = Canvas.Image
  , fs = require('fs');

var draw = function (img) {
      var w = img.width;
      var h = img.height;
      var canvas = new Canvas(w, h);
      var ctx = canvas.getContext('2d');

      ctx.drawImage(img, 0, 0, w, h, 0, 0, w, h);

      var out = fs.createWriteStream(__dirname + '/foo.jpg');
      var stream = canvas.createJPEGStream({
        bufsize: 2048,
        quality: 80
      });
      stream.pipe(out);
};

That breaks because we are trying to draw an Image created using a different required canvas than that one we are using to draw the image. The following error is reported:

/home/foo/other/other.js:100
        ctx.drawImage(img, 0, 0, w, h, 0, 0, w, h);
              ^
TypeError: Image or Canvas expected

A possible fix is to both modules require the same node-canvas. However, this is just a temporary fix.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions