I have:
<div id="canvasContainer">
<canvas id="myCanvas" height="450" width="650"></canvas>
</div>
and:
var myCanvas = $("#myCanvas");
var myCanvasContext = myCanvas.getContext("2d");
yet I get:
Uncaught TypeError: myCanvas.getContext is not a function
when the page is loaded.
When I try something like:
myCanvas.click (function() {
console.log("You clicked the canvas");
});
the reference to myCanvas
works perfectly. What gives?
getContext
is not a part of jQuery library, it's a part of WebAPI. You have to reference the raw DOM Node object instead of jQuery wrapper:
var myCanvas = $("#myCanvas");
var myCanvasContext = myCanvas[0].getContext("2d");
(what [0]
does is it references the underlying DOM Node that jQuery wrapper hides from you).
Your "click" example works, because element.click
(in your case) is actually a part of jQuery library API: https://api.jquery.com/click/
myCanvas
in your code is a jQuery object, not a DOM element ...
use the following code instead
var myCanvas = document.getElementById("myCanvas");
var myCanvasContext = myCanvas.getContext("2d");
of course, then myCanvas.click(...)
wont work, but you can always do
$(myCanvas).click(...)
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