开发者

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.na开发者_Python百科turalHeight;
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?


I suspect the problem with the first snippet is that document is a XUL document, so its createElement function will create a XUL element and there is no such thing as a XUL:canvas. It is possible to create HTML elements in a XUL document, but then you'll want to use createElementNS(). To be more clear the code would look like

document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");

Why src_data comes out empty though, I don't know.


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.


I think you should use

content.document.createElement()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜