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?
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.
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.
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]
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With