CAFxX CAFxX - 7 months ago 9
Javascript Question

Manipulating <canvas> image data in Firefox extension

In my extension I'd like to manipulate some images. So I'm trying to read their raw pixels using canvas.
The problem is that if, in chrome code, I execute (

img
is an image in a content document):

var src = document.createElement("canvas");
src.width = img.naturalWidth;
src.height = img.naturalHeight;
var srcCtx = src.getContext("2d");


on the last line it says that
getContext
is not a function.
On the other hand if I run (notice that the first line is different!):

var src = img.ownerDocument.createElement("canvas");
src.width = img.naturalWidth;
src.height = img.naturalHeight;
var srcCtx = src.getContext("2d");
srcCtx.drawImage(img, 0, 0);
var src_data = srcCtx.getImageData(0, 0, src.width, src.height);


no error is returned, but
src_data
comes out empty. I suppose it may have something to do with accessing web content from chrome code. Any suggestion?

Answer

As I said above, the problem was in a different piece of code.

It was actually due to the fact that I misread the documentation and thought that src_data was supposed to contain the pixels, whereas it should have been src_data.data. For some reason that I can't understand printing out uneval(src_data) would return ({}) instead, whereas in it there should be three members, data, width and height.