I wrote an Html file that contains some javascript code. It is an Html5 file, so I add a canvas in the Html source code and get the canvas context object with the code move_canvas.getContext(ā2dā);. But when I browse the Html5 file in a web browser, it shows the error message Uncaught TypeError: move_canvas.getContext is not a function in the browser inspector console, this article will tell you how to fix it.
1. How To Debug & Fix The Canvas.getContext Is Not A Function Javascript Error.
- Open the Html file in a web browser such as Google Chrome.
- Right-click the web page screen in the web browser, then click the Inspect menu item to open the browser inspector.
- Click the Sources tab on the inspector, then select the javascript js file or Html file below the Sources tab.
- Click the first column in the js code to set a breakpoint at the code that throws the canvas.getContext is not a function error.
- Now run the javascript code until it stops at the breakpoint.
- Hover the mouse pointer on the canvas object, it will show you the Html object attributes list with the title canvas#move-canvas.
- The text before the # charactor is the Html element type, it should be canvas because we just add the canvas object.
- The text after the # charactor is the Html element id.
- In my example, the Html element debug info is input#move-canvas.
- From the above info, we can see the Html object is an input element in my example, it is not a canvas element.
- The Html input element has the same id as the canvas element, and the input element does not have the getContext() function.
- Then when it runs to the code line canvas.getContext(ā2dā);, it will throw the error Uncaught TypeError: move_canvas.getContext is not a functionĀ because the Html input element doese not have the getContext(ā2dā) function.
- After I change the input elementās id to a different one from the canvas elementās id, the error has been fixed.
- I also find another signal that can be used to find the cause, that is when I assign the width or height value to the canvas object ( canvas.width = canvasWidth; ), the canvas objectās width is always 0 because the Html input element does not support the width attribute.