Solve - getContext is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 28, 2022

banner

Check out my new book

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 instead of a canvas element.

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

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're not misspelling getContext (method names are case-sensitive).

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.