为什么canvas不能使用jQuery选择器? [英] Why canvas doesn't work with jQuery selector?
问题描述
例如:
strong> window.onload = function(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.fillRect(10,50,100,200);
};
window.onload = function(){
var canvas = $('#myCanvas');
var ctx = canvas.getContext('2d');
ctx.fillRect(10,50,100,200);
};
所以我不知道为什么会发生。是否有任何限制?
检查您的jQuery小提琴的更新版本:http://jsfiddle.net/techfoobar/46VKa/3/
问题是:
var canvas = $('#myCanvas')
获取一个jQuery扩展对象,而不是一个本地DOM元素对象它有成员函数像getContext等。对于这个,你需要使用 var canvas = $('#myCanvas')[0]
注意: var canvas = document.getElementById('myCanvas');
$ c> var canvas = $('#myCanvas')[0]
I have made simple example of using canvas and then I saw that my code doesn't work when I use jQuery selector.
Examples:
window.onload = function() {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.fillRect(10,50,100,200);
};
window.onload = function() {
var canvas = $('#myCanvas');
var ctx = canvas.getContext('2d');
ctx.fillRect(10,50,100,200);
};
So I have no idea why it happened. Is there any limitations about it?
Check this updated version of your jQuery fiddle: http://jsfiddle.net/techfoobar/46VKa/3/
The problem was:
var canvas = $('#myCanvas')
gets you a jQuery extended object and not a native DOM element object that has member functions like getContext etc. For this, you need to get the canvas element using var canvas = $('#myCanvas')[0]
NOTE: var canvas = document.getElementById('myCanvas');
is equivalent to var canvas = $('#myCanvas')[0]
这篇关于为什么canvas不能使用jQuery选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!