0Pricing
JavaScript Academy · Lesson

Setting Up the Canvas Context

Get and configure the 2D rendering context.

What Is the Canvas API?

The Canvas API lets you draw 2D graphics with JavaScript onto a <canvas> element. You get a drawing surface made of pixels and a set of commands to paint shapes, images, and text.

  • The markup is a single <canvas> tag.
  • All drawing happens in JavaScript through a context object.
<canvas id="board" width="320" height="200"></canvas>

Getting the Context

Call getContext('2d') on the canvas element to get a CanvasRenderingContext2D. Every drawing command goes through this object.

const canvas = document.getElementById("board");
const ctx = canvas.getContext("2d");
console.log(ctx.constructor.name); // CanvasRenderingContext2D

All lessons in this course

  1. Setting Up the Canvas Context
  2. Drawing Shapes and Paths
  3. Working with Images and Text
  4. Animation with requestAnimationFrame
← Back to JavaScript Academy