Reputation: 23
I am developing a Firefox extension that uses the canvas element. It is added programatically (The canvas element is not there from the beginning, it is created and then I try to append).
The code used in the XUL (the mozilla XML) in very simple, adds NO elements, and only loads the script using the common tag.
The problems i've faced are, first, when the line var myCtx = myCanvas.getContext("2d"); runs, the firefox console error returns TypeError: myCanvas.getContext is not a function.
Then, the other error is, even if I dont try to paint the canvas or anything, when I run the code, the line that appends the canvas to the body of the document also does not work, returning that document.body is undefined.
The script is as follows:
endSelectBox : function(aEvent){
mouseX2 = aEvent.clientX;
mouseY2 = aEvent.clientY;
//Start creating new canvas to be added in this position.
var canvasWidth, canvasHeight;
canvasWidth = Math.abs(mouseX2 - mouseX); //Calculates canvas width to be used.
canvasHeight = Math.abs(mouseY2 - mouseY); //Calculates canvas height to be used.
alert("pre id height width");
//Set canvas values for size.
var myCanvas;
myCanvas = document.createElement("canvas");
myCanvas.setAttribute("id", "canvas1");
myCanvas.setAttribute("height", canvasHeight.toString());
myCanvas.setAttribute("width", canvasHeight.toString());
//Set canvas fixed position on the page.
alert("pre CSS");
var top = Math.max(mouseY, mouseY2);
top = top.toString();
top = top + "px";
var left = Math.min(mouseX, mouseX2);
left = left.toString();
left = left + "px";
myCanvas.style.top = top;
myCanvas.style.left = left;
//myCanvas.style.position = "fixed";
//Paint canvas interior. //Not working because getContext returns null. No idea why, try to figure this out.
alert("pre painting");
var myCtx = myCanvas.getContext("2d");
alert("pre fillstyle");
myCtx.fillStyle = "#150000";
alert("pre fillrect");
myCtx.fillRect(0,0, canvasWidth - 1, canvasHeight - 1);
document.body.appendChild(myCanvas);// This never runs. WHY??
alert("worked");
}
Upvotes: 0
Views: 1148
Reputation: 23
The solution was to create the element using the document.createElementNS() function, and also when accessing the document, as user powerc9000 said, we need to use content.document in order to access it properly. Cheers!
Upvotes: 1
Reputation: 2103
When making an extenion in Firefox from this link
To get the document of the current webpage from a browser.xul overlay, you should use content.document, instead of just document which is the document of the browser's window itself.
So try changing all your document
with content.document
that should solve your problem.
Upvotes: 0