为什么canvas不能使用jQuery选择器? [英] Why canvas doesn't work with jQuery selector?

查看:451
本文介绍了为什么canvas不能使用jQuery选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如:

strong>



JavaScript

  window.onload = function(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

ctx.fillRect(10,50,100,200);
};

JQuery

  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:

Javascript

    window.onload = function() {
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        ctx.fillRect(10,50,100,200);
    };

JQuery

   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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆