Solve - getContext is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Wade Lambert

Solve - getContext is not a function Error #

The "getContext is not a function" error occurs when the getContext() method is called on a value that is not a canvas DOM element. To solve the error, make sure to only call the getContext method on canvas elements.

typeerror getcontext is not a function

Here is an example of how the error occurs.

index.js
const canvas = document.getElementsByClassName('canvas'); console.log(canvas); // ๐Ÿ‘‰๏ธ [canvas.canvas] // โ›”๏ธ TypeError: getContext is not a function const ctx = canvas.getContext('2d');

We called the getContext method on a NodeList and not a canvas element and got the error back.

To solve the error, console.log the value you're calling the getContext() method on and make sure it's a canvas element.

Here is a complete working example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <canvas class="canvas" width="500" height="500"></canvas> <!-- โœ… Your JS script here โœ… --> <script src="index.js"></script> </body> </html>
Notice that we placed the JS script tag at the bottom of the body tag, after all the DOM elements have been declared. Had we placed the script tag before the DOM elements have been declared, we wouldn't be able to access the canvas element.

Here is the related JavaScript code.

index.js
const canvas = document.getElementsByClassName('canvas'); console.log(canvas); // ๐Ÿ‘‰๏ธ [canvas.canvas] const ctx = canvas[0].getContext('2d'); console.log(ctx); // ๐Ÿ‘‰๏ธ CanvasRenderingContext2D

Because the getElementsByClassName method returns a NodeList and not a DOM element, we had to access the element at index 0 to get a DOM element, on which we called the getContext method.

If the error persists, console.log the value you're calling the getContext method on and make sure it's a canvas element.

If it's a jQuery object, you have to convert it to a DOM element before calling the getContext method.

index.js
const canvas = $('.canvas'); console.log(canvas); // ๐Ÿ‘‰๏ธ [canvas.canvas] const ctx = canvas[0].getContext('2d'); console.log(ctx); // ๐Ÿ‘‰๏ธ CanvasRenderingContext2D

If you're still getting the error make sure you're not misspelling getContext (it's case sensitive).

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee