Skip to content

Canvas API

In one line

The Canvas API lets you draw 2D graphics — shapes, text, images — pixel by pixel on an HTML canvas element.

In simple words

The Canvas API provides a drawable surface (a <canvas> element) and a 2D rendering context you control with JavaScript. You issue drawing commands — fill rectangles, stroke paths, draw text, render images — and the browser paints pixels onto the canvas. It is imperative: you describe each drawing operation.

Canvas is ideal for games, data visualizations, image editors, and any dynamic graphics where you redraw frequently. Because you manipulate pixels directly, it is very fast for complex scenes, but the drawings are not part of the DOM — you cannot attach event listeners to individual shapes.

The workflow is: get the canvas element, obtain its 2d context, set fill/stroke styles, and call drawing methods. For animation, you clear and redraw on each frame using requestAnimationFrame. For 3D, use WebGL (a canvas context based on OpenGL).

Example

javascript
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

// Draw a blue rectangle
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 100, 50);

// Draw text
ctx.fillStyle = "white";
ctx.font = "20px sans-serif";
ctx.fillText("Hello Canvas", 20, 40);

getContext('2d') returns the drawing context. fillRect paints a blue rectangle, fillText draws white text on top.

Related terms

Related Resources

Related Lessons

  • Canvas

    Learn 2D drawing with Canvas.

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary