Javascript jQuery 相当于获取 Canvas 的上下文
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2925130/
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
jQuery equivalent of getting the context of a Canvas
提问by Claudiu
I have the following working code:
我有以下工作代码:
ctx = document.getElementById("canvas").getContext('2d');
Is there any way to re-write it to use $? Doing this fails:
有没有办法重新编写它以使用$?这样做失败:
ctx = $("#canvas").getContext('2d');
回答by Matt
Try:
尝试:
$("#canvas")[0].getContext('2d');
jQuery exposes the actual DOM element in numeric indexes, where you can perform normal JavaScript/DOM functions.
jQuery 在数字索引中公开实际的 DOM 元素,您可以在其中执行普通的 JavaScript/DOM 功能。
回答by OG Sean
I have also seen that it's often preferred to use .get(0) to reference a jquery target as HTML element:
我还看到,通常更喜欢使用 .get(0) 将 jquery 目标引用为 HTML 元素:
var myCanvasElem = $("#canvas").get(0);
Perhaps to help avoid any potential null object references since jquery returns null as an object but working with the element from .get(0) may not fail so silently... You can easily check if the canvas was found first before .get(0) like
也许是为了帮助避免任何潜在的空对象引用,因为 jquery 将 null 作为对象返回,但是使用 .get(0) 中的元素可能不会如此无声地失败......您可以轻松检查画布是否在 .get(0) 之前首先被找到) 喜欢
if( $("#canvas").length ) ctx = $("#canvas").get(0).getContext('2d');
else console.log('Error: Canvas not found with selector #canvas');
回答by MistyDawn
try{
ctx = $('#canvas').get(0).getContext('2d');
}catch(e){
console.log('We have encountered an error: ' + e);
}
or...
或者...
if( typeof $('#canvas') === 'undefined'){
var canvas = '<canvas id="canvas"><\/canvas>';
$('body').append(canvas);
}
setTimeout( function(){ ctx = $('#canvas').get(0).getContext('2d'); }, 500);
Using setTimeout is an easy way to ensure you don't try calling the canvas element before it's fully created and registered to the DOM.
使用 setTimeout 是一种简单的方法,可以确保在完全创建并注册到 DOM 之前不要尝试调用 canvas 元素。
回答by александр лобазов
The script works before it finds "canvas"
脚本在找到“画布”之前工作
$(document).ready(function() {
ctx = $("#canvas");
});

