Why canvas doesn't work with jQuery selector?

前端 未结 4 1376
太阳男子
太阳男子 2020-12-29 07:10

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

<
相关标签:
4条回答
  • 2020-12-29 07:34
    window.onload = function() {
         var canvas = $('#myCanvas');
         var ctx = canvas[0].getContext('2d'); // not canvas.getContext('2d')
                
         ctx.fillRect(10,50,100,200);
    };
    

    in your code you're using canvas.getContext('2d');, but it should be canvas[0].getContext('2d');.

    Because getContext('2d') works on DOM element, where var canvas = $('#myCanvas'); return a jQuery object but node a DOM element.

    And to retrieve a DOM element (here, canvas element) from jQuery object you need to use canvas[0].


    In you JavaScript code you're using:

    document.getElementById('myCanvas'); which returns a DOM element. So,

    var canvas = $('#myCanvas');

    canvas[0] and document.getElementById('myCanvas'); are same.


    You can also change the jQuery code like:

     window.onload = function() {
         var canvas = $('#myCanvas')[0]; // get the element here
         var ctx = canvas.getContext('2d');
                
         ctx.fillRect(10,50,100,200);
    };
    
    0 讨论(0)
  • 2020-12-29 07:36

    You can use get function of jquery to retrieve canvas element.

    var canvas = $('#myCanvas').get(0).getContext('2d');
    
    0 讨论(0)
  • 2020-12-29 07:41

    This code...

    var canvas = $('#myCanvas');
    var ctx = canvas.getContext('2d');
    

    Needs to be...

    var canvas = $('#myCanvas');
    var ctx = canvas[0].getContext('2d');
    
    0 讨论(0)
  • 2020-12-29 07:42

    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]

    0 讨论(0)
提交回复
热议问题