我正在开发一个使用canvas元素的Firefox扩展。它是以编程方式添加的( Canvas 元素从一开始就不存在,它是创建的,然后我尝试附加)。
XUL(mozilla XML)中使用的代码非常简单,不添加任何元素,并且仅使用通用标记加载脚本。
我遇到的问题首先是当线路 var myCtx = myCanvas.getContext("2d"); 运行时,firefox控制台错误返回TypeError: myCanvas.getContext is not a function.
然后,另一个错误是,即使我不尝试绘制 Canvas 或任何东西,当我运行代码时,将 Canvas 附加到文档正文的行也不起作用,返回 document.body未定义。
脚本如下:
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");
}
最佳答案
解决方案是使用 document.createElementNS() 函数创建元素,并且在访问文档时,正如用户 powerc9000 所说,我们需要使用 content.document 才能正确访问它。 干杯!
关于javascript - 类型错误 : myCanvas. getContext 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23962685/