Last updated: Mar 3, 2024
Reading timeยท2 min

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.

Here is an example of how the error occurs.
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.
getContext method on canvas elementsTo 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.
<!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.
canvas element.Here is the related JavaScript code.
const canvas = document.getElementsByClassName('canvas'); console.log(canvas); // ๐๏ธ [canvas.canvas] const ctx = canvas[0].getContext('2d'); console.log(ctx); // ๐๏ธ CanvasRenderingContext2D

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