Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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?

like image 420
Nisten Avatar asked Sep 05 '16 00:09

Nisten


2 Answers

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/

like image 163
mdziekon Avatar answered Nov 12 '22 10:11

mdziekon


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(...)
like image 28
Jaromanda X Avatar answered Nov 12 '22 10:11

Jaromanda X