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 = $('#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.
window.onload = function() {
var canvas = $('#myCanvas')[0]; // get the element here
var ctx = canvas.getContext('2d');
ctx.fillRect(10,50,100,200);
};
You can use get function of jquery to retrieve canvas element.
var canvas = $('#myCanvas').get(0).getContext('2d');
This code...
var canvas = $('#myCanvas');
var ctx = canvas.getContext('2d');
Needs to be...
var canvas = $('#myCanvas');
var ctx = canvas[0].getContext('2d');
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]