Nisten Nisten - 1 year ago 81
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>


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: (function() {
console.log("You clicked the canvas");

the reference to
works perfectly. What gives?

Answer Source

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 (in your case) is actually a part of jQuery library API:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download