Borislav Hadzhiev
Last updated: Jul 28, 2022
Check out my new book
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.
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.
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.
<!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>
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're not misspelling getContext
(method names are case-sensitive).