Nisten Nisten - 2 months ago 6
Javascript Question

"getContext is not a function" when using variable for element selector

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?

Answer

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 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/

Comments