我有以下工作代码:
ctx = document.getElementById("canvas").getContext('2d');
有没有办法重新编写它以使用$
?这样做失败了:
ctx = $("#canvas").getContext('2d');
答案 0 :(得分:259)
尝试:
$("#canvas")[0].getContext('2d');
jQuery在数字索引中公开实际的DOM元素,您可以在其中执行常规的JavaScript / DOM函数。
答案 1 :(得分:12)
我还看到,通常首选使用.get(0)将jquery目标作为HTML元素引用:
var myCanvasElem = $("#canvas").get(0);
也许是为了帮助避免任何潜在的空对象引用,因为jquery将null作为对象返回,但是使用.get(0)中的元素可能不会如此默默地失败...您可以轻松地检查是否先找到了画布。得到(0)像
if( $("#canvas").length ) ctx = $("#canvas").get(0).getContext('2d');
else console.log('Error: Canvas not found with selector #canvas');
答案 2 :(得分:1)
try{
ctx = $('#canvas').get(0).getContext('2d');
}catch(e){
console.log('We have encountered an error: ' + e);
}
或...
if( typeof $('#canvas') === 'undefined'){
var canvas = '<canvas id="canvas"><\/canvas>';
$('body').append(canvas);
}
setTimeout( function(){ ctx = $('#canvas').get(0).getContext('2d'); }, 500);
使用setTimeout是确保您在画布元素完全创建并注册到DOM之前不要尝试调用它的简便方法。
答案 3 :(得分:-4)
脚本在找到&#34; canvas&#34;
之前有效 $(document).ready(function() {
ctx = $("#canvas");
});