Get IntelliSense in VS Code for HTML Canvas

Published: Sunday, July 5, 2020

Greetings, friends! Has this ever happened to you?

using canvas api with no intellisense in vs code

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:

Copied! ⭐️
/** @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! 😃

using canvas api with intellisense in vs code

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.

intellisense for the fillRect method in vs code

This approach to adding type hints not only applies to the HTML Canvas! You can add type hints for other parts of the DOM API or even other libraries. Since JSDoc is supported natively in VS Code, you can add annotations to help document your own libraries as well as third party libraries as well. If you are working on a big project and/or want better type support, I would suggest using TypeScript instead.

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! :)