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

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(...)

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/