Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why canvas doesn't work with jQuery selector?

Tags:

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?

like image 861
Mateusz Rogulski Avatar asked Jul 20 '12 06:07

Mateusz Rogulski


People also ask

Does canvas use jQuery?

The direct answer is no because jQuery is based on DOM querying and manipulation. Canvas elements are drawn using the Canvas API with JavaScript. If you're looking for a good canvas library, you might try out KineticJS.

Does HTML5 canvas use jQuery to draw on the screen?

HTML5 Canvas Sketchpad (Drawing) App will allow users to draw lines, scribble, write, sketch, etc. with mouse and touch screen. Inside the jQuery document ready event handler, the jQuery HTML5 Sketch plugin is applied to the HTML5 Canvas element.


2 Answers

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]

like image 141
techfoobar Avatar answered Oct 11 '22 12:10

techfoobar


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);
};
like image 32
thecodeparadox Avatar answered Oct 11 '22 10:10

thecodeparadox