TypeError: getContext is not a function in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 3, 2024
2 min

banner

# TypeError: getContext is not a function in JavaScript

The "TypeError: 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 instead of a canvas element.

# Only call the getContext method on canvas elements

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>

move js script tag to bottom of body tag

The code for this article is available on GitHub

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 above the code that declares the DOM elements, 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

calling getcontext method on canvas elements

The code for this article is available on GitHub

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 still get the error, make sure you aren't misspelling getContext (method names are case-sensitive).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev