Canvas: getContext()
The getContext() method returns the drawing context for a canvas, such as the 2D context.
What you will learn
- How to request a 2D drawing context
- Why you should check for a missing context
- How the context connects the canvas to drawing methods
Basic example
const canvas = document.querySelector('#scene'); const context = canvas.getContext('2d'); if (context) { context.fillRect(20, 20, 100, 60); }The string '2d' selects the Canvas 2D API. A browser or environment may return null, so do not call drawing methods until you have a context.
Common mistakes
- Call
getContext()on the canvas element, not on its parent. - Do not confuse the drawing context with the canvas element itself.
- Keep a text alternative near important visual information.