1

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?

Greg
  • 5,422
  • 1
  • 27
  • 32
CAFxX
  • 28,060
  • 6
  • 41
  • 66

3 Answers3

2

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.

Greg
  • 5,422
  • 1
  • 27
  • 32
Tyler
  • 21,762
  • 11
  • 61
  • 90
  • can you tell me with which `NameSpace` can we create a `canvas` element from the firefox extension. I'm struggling a lot and getting the following error when I tried creating `canvas` using `document.createElement("canvas"); ` `NS_ERROR_NOT_AVAILABLE Component is not available` – Vinothkumar Arputharaj Jun 09 '11 at 10:54
  • Canvas is an HTML element, so you need the HTML (or XHTML) namespace, `http://www.w3.org/1999/xhtml` – Tyler Jun 09 '11 at 17:18
1

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.

CAFxX
  • 28,060
  • 6
  • 41
  • 66
0

I think you should use

content.document.createElement()
Thiem Nguyen
  • 6,345
  • 7
  • 30
  • 50
rlib
  • 7,444
  • 3
  • 32
  • 40