Automattic / Automattic/node-canvas

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

Open
#487 6 comments 12 reactions 0 assignees View on GitHub
Bug
Dominant language
JavaScript
Stars
10.7k
Forks
1.2k
Avg merge
4d 8h
Merged PRs (30d)
1

Description

As previously reported at https://github.com/Automattic/node-canvas/issues/338#issuecomment-57951547, 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.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.