Get IntelliSense in VS Code for HTML Canvas
Greetings, friends! Has this ever happened to you?
You're trying to get IntelliSense for things in the DOM API like the HTML Canvas, but it's not there! 😲
VS Code obviously knows about common browser methods. As seen in the screenshot, it automatically will suggest getBoundingClientRect
, but what we want is IntelliSense for the HTML Canvas! Luckily, for us, VS Code allows you to insert type hints, a syntax you might be familiar with if you use JSDoc for documenting your JavaScript code. That's because VS Code has JSDoc support built-in!
To add IntelliSense in VS Code for recognizing the "canvas" type, we need to add a type hint like so:
/** @type {HTMLCanvasElement} */
const c = document.getElementById('canvas')
Now, when we start typing, VS Code will understand that document.getElementById('canvas') returns an object of type HTMLCanvasElement
and help autocomplete methods that belong to this type. WOW! So helpful! 😃
You can find out this type by looking at the documentation on MDN Web Docs about the Canvas API. VS Code will now even be able to find methods that belong to the CanvasRenderingContext2D
interface such as the fillRect()
method. See the fillRect documentation at MDN for more details.
If you're performing a small experiment with vanilla JavaScript, then this approach for adding IntelliSense can definitely be a quality of life improvement. Have fun! Happy coding! :)