getContext() The HTMLCanvasElement. getContext() method returns a drawing context on the canvas, or null if the context identifier is not supported, or the canvas has already been set to a different context mode.
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.
The CanvasRenderingContext2D interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of a <canvas> element. It is used for drawing shapes, text, images, and other objects.
The HTML <canvas> element is used to draw graphics on a web page. The graphic to the left is created with <canvas> . It shows four elements: a red rectangle, a gradient rectangle, a multicolor rectangle, and a multicolor text.
Try:
$("#canvas")[0].getContext('2d');
jQuery exposes the actual DOM element in numeric indexes, where you can perform normal JavaScript/DOM functions.
I have also seen that it's often preferred to use .get(0) to reference a jquery target as HTML element:
var myCanvasElem = $("#canvas").get(0);
Perhaps to help avoid any potential null object references since jquery returns null as an object but working with the element from .get(0) may not fail so silently... You can easily check if the canvas was found first before .get(0) like
if( $("#canvas").length ) ctx = $("#canvas").get(0).getContext('2d');
else console.log('Error: Canvas not found with selector #canvas');
try{
ctx = $('#canvas').get(0).getContext('2d');
}catch(e){
console.log('We have encountered an error: ' + e);
}
or...
if( typeof $('#canvas') === 'undefined'){
var canvas = '<canvas id="canvas"><\/canvas>';
$('body').append(canvas);
}
setTimeout( function(){ ctx = $('#canvas').get(0).getContext('2d'); }, 500);
Using setTimeout is an easy way to ensure you don't try calling the canvas element before it's fully created and registered to the DOM.
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