javascript - 类型错误 : myCanvas. getContext 不是函数

标签 javascript html firefox canvas

我正在开发一个使用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/

相关文章:

javascript - 对这个数组进行排序的算法

CSS 箭头(使用 :after) looks different in Firefox and Chrome

html - 为什么显示:block affect vertical alignment in Firefox?

javascript - 在浏览器中测量和基准测试 javascript 引擎的处理能力

javascript - Razor/JavaScript 和尾随分号

javascript - 自动完成部分滚动

javascript - 从 index.html 打开 quiz.html 页面时怀疑 javascript 未加载

c# - 如何在 C# 中去除 html 标签

html - 使用CSS在悬停时更改图片内的图片

html - Bootstrap 4 : Don’t want dropdown items inside the navbar container