- 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 first column in the js code to set a breakpoint at the code that throws the canvas.getContext is not a function error.
- 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.