Javascript 将变量用于元素选择器时,“getContext 不是函数”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39322503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"getContext is not a function" when using variable for element selector
提问by Nisten
I have:
我有:
<div id="canvasContainer">
<canvas id="myCanvas" height="450" width="650"></canvas>
</div>
and:
和:
var myCanvas = $("#myCanvas");
var myCanvasContext = myCanvas.getContext("2d");
yet I get:
但我得到:
Uncaught TypeError: myCanvas.getContext is not a function
未捕获的类型错误:myCanvas.getContext 不是函数
when the page is loaded.
页面加载时。
When I try something like:
当我尝试类似的事情时:
myCanvas.click (function() {
console.log("You clicked the canvas");
});
the reference to myCanvas
works perfectly. What gives?
对myCanvas
作品的引用完美无缺。是什么赋予了?
回答by mdziekon
getContext
is not a part of jQuery library, it's a part of WebAPI. You have to reference the raw DOM Node object instead of jQuery wrapper:
getContext
不是 jQuery 库的一部分,而是 WebAPI 的一部分。您必须引用原始 DOM 节点对象而不是 jQuery 包装器:
var myCanvas = $("#myCanvas");
var myCanvasContext = myCanvas[0].getContext("2d");
(what [0]
does is it references the underlying DOM Node that jQuery wrapper hides from you).
([0]
它引用了 jQuery 包装器向您隐藏的底层 DOM 节点是什么意思)。
Your "click" example works, because element.click
(in your case) is actually a part of jQuery library API: https://api.jquery.com/click/
您的“单击”示例有效,因为element.click
(在您的情况下)实际上是 jQuery 库 API 的一部分:https: //api.jquery.com/click/
回答by Jaromanda X
myCanvas
in your code is a jQuery object, not a DOM element ...
myCanvas
在您的代码中是一个 jQuery 对象,而不是一个 DOM 元素......
use the following code instead
改用以下代码
var myCanvas = document.getElementById("myCanvas");
var myCanvasContext = myCanvas.getContext("2d");
of course, then myCanvas.click(...)
wont work, but you can always do
当然,那是myCanvas.click(...)
行不通的,但你总能做到
$(myCanvas).click(...)
回答by u6741575
var myCanvas = $("#myCanvas");
get a JQuery Object,you need to do like this
var myCanvas = $("#myCanvas");
得到一个JQuery对象,你需要这样做
var myCanvasContext = myCanvas[0].getContext("2d");
myCanvas[0] is a DOM Object,
myCanvas[0] 是一个 DOM 对象,
Suggest that you express jquery object like this
建议你像这样表达jquery对象
var $myCanvas = $("#myCanvas")
回答by Delino
Use the html5 canvas element instead of creating an element using id.
Eg. <canvas></canvas>
使用 html5 canvas 元素而不是使用 id 创建元素。例如。<canvas></canvas>
var canvas = document.getElementById("canvas");
context = canvas.getContext('2d');
base_image = new Image();
base_image.src = imageUrl;
base_image.onload = function(){
context.drawImage(base_image, 0, 0);
}