Canvas: getContext()

The getContext() method returns the drawing context for a canvas, such as the 2D context.

What you will learn

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