Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 122 ยท Graphics

Canvas Basics

Get started with the HTML canvas element. Draw rectangles with the 2D context, set fill and stroke styles, size the canvas sharply and provide fallback content.

The <canvas> element gives you a blank rectangle of pixels and a JavaScript API to paint on it. Games, photo editors, charting libraries, signature pads, generative art and data visualizations with thousands of points are often built on canvas, because it can draw a huge amount of graphics very quickly.

Canvas works very differently from SVG. In SVG, every shape is an element in the page that you can style and change later. A canvas is more like a painting: once you've drawn a rectangle, the canvas only remembers the colored pixels, not the rectangle. To change the picture, you paint over it or clear it and draw again. In this lesson you'll set up a canvas, draw and color rectangles, learn the important difference between a canvas's size and its displayed size, and provide content for people who can't see it.

The canvas element and its context

A canvas needs two things in HTML: an id (or another way to find it) and a size.

HTML
<canvas id="board" width="400" height="200">
  A drawing of three colored squares.
</canvas>

On its own, the element is transparent and empty. To draw, you ask it for a rendering context, an object with all the drawing methods. For flat, two-dimensional graphics, that's the "2d" context:

JavaScript
const canvas = document.querySelector("#board");
const ctx = canvas.getContext("2d");

By convention the context is stored in a variable called ctx. Other context types exist, such as "webgl" and "webgl2" for hardware-accelerated 3D, but the 2D context is the place to start, and it's what this lesson and the next use.

Coordinates

Like SVG, canvas puts the origin (0, 0) at the top-left corner. The x-axis points right and the y-axis points down. One unit is one canvas pixel. A canvas with width="400" and height="200" has coordinates from (0, 0) to (400, 200).

Drawing rectangles

Rectangles are the only shape with dedicated one-step methods:

Method What it does
ctx.fillRect(x, y, width, height) Paints a filled rectangle
ctx.strokeRect(x, y, width, height) Paints a rectangle's outline
ctx.clearRect(x, y, width, height) Erases a rectangle back to transparent
Filling, stroking and clearing

The orange rectangle covers part of the blue one, because it was drawn later. The cleared hole shows the page background through the canvas. Try changing the order of the calls and see how the picture changes.

Fill and stroke styles

The context has state: settings that stay in effect for every drawing call until you change them. The most important ones are:

Property Default Meaning
fillStyle "#000000" Color (or gradient, or pattern) used by fill operations
strokeStyle "#000000" Color (or gradient, or pattern) used by stroke operations
lineWidth 1 Thickness of strokes, in canvas pixels
globalAlpha 1 Transparency applied to everything drawn, from 0 to 1

fillStyle and strokeStyle accept any CSS color: names like "teal", hex like "#0f766e", or functions like "rgb(15 118 110 / 0.5)" and "hsl(170 80% 30%)". See Colors for all the formats.

Because settings persist, set them right before the drawing that needs them. When you want to change settings temporarily, wrap the drawing in ctx.save() and ctx.restore(): save() pushes the current state onto a stack and restore() brings it back.

JavaScript
ctx.save();
ctx.globalAlpha = 0.3;
ctx.fillStyle = "purple";
ctx.fillRect(10, 10, 50, 50);
ctx.restore();   // back to full opacity and the previous fillStyle

Strokes are centered on the shape's edge, exactly as in SVG. A 1-pixel line drawn exactly on a whole-number coordinate is split across two pixel columns and can look blurry; drawing it at x + 0.5 puts it squarely on one pixel.

An interactive canvas

Since the canvas doesn't remember shapes, interactivity means listening for events, computing where they happened and drawing in response. Here, each click paints a square where you clicked:

Click to paint

The click position comes in page coordinates. Subtracting the canvas's position (from getBoundingClientRect()) converts it to coordinates relative to the canvas, and multiplying by pad.width / box.width corrects for any difference between the canvas's pixel size and its displayed size. That difference is the topic of the next section.

Canvas size vs CSS size

A canvas has two sizes, and mixing them up is the most common canvas mistake:

  1. The bitmap size: how many pixels the canvas contains. Set it with the width and height attributes (or the canvas.width and canvas.height properties). The default is 300 ร— 150.
  2. The display size: how big it appears on the page. By default it matches the bitmap size, but CSS width and height can change it.

If the two differ, the browser stretches the bitmap, just like an image. Draw on a 100 ร— 50 canvas displayed at 400 ร— 200 and every canvas pixel becomes a blurry 4 ร— 4 block:

Same drawing, different bitmap sizes

Both canvases take up the same space, but the first has only 60 ร— 30 real pixels, so its text and shape are blocky.

Setting width or height clears the canvas. Assigning either property, even to the same value, erases the drawing and resets all context state (colors, line width and so on). Set the size first, then draw.

Sharp canvases on high-resolution screens

Phones and many laptops have screens with more than one physical pixel per CSS pixel. The ratio is available as window.devicePixelRatio (often 2 or 3). A canvas whose bitmap matches its CSS size looks slightly soft on those screens. The usual fix is to make the bitmap bigger by that ratio and scale the drawing to match:

JavaScript
const ratio = window.devicePixelRatio || 1;
const cssWidth = 400;
const cssHeight = 200;

canvas.style.width = `${cssWidth}px`;
canvas.style.height = `${cssHeight}px`;
canvas.width = Math.round(cssWidth * ratio);
canvas.height = Math.round(cssHeight * ratio);

ctx.scale(ratio, ratio);   // now draw in CSS pixels as usual

Fallback content and accessibility

Content between <canvas> and </canvas> is fallback content. Browsers that render the canvas don't display it, but it's shown when the canvas can't be used (for example, when JavaScript is turned off), so describe what the canvas would show or offer an alternative.

A canvas is just pixels to assistive technology. A screen reader can't know that you drew a bar chart with five bars. So:

  • For a meaningful image, add role="img" and an aria-label that describes it, or put the real data next to it in a table.
  • For interactive canvases, such as games and editors, provide keyboard controls and expose important state as real text elsewhere on the page.
  • Never draw text as the only way to deliver information. Text in a canvas can't be selected, translated, searched or resized by the reader.
HTML
<canvas width="400" height="200" role="img"
        aria-label="Monthly sales rose from 120 in January to 310 in June.">
  <p>Monthly sales rose from 120 in January to 310 in June.</p>
</canvas>

Canvas or SVG?

Canvas SVG
Model Pixels; draw and forget Shapes as elements in the page
Scaling Can get blurry if resized Always sharp
Many objects (thousands) Fast Can get slow
Events on individual shapes You compute hits yourself Built in: shapes are elements
Styling with CSS No (only the element itself) Yes
Accessibility You must add it Text and structure are available

Choose SVG for icons, logos, diagrams and charts with a modest number of parts. Choose canvas for games, particle effects, image processing and visualizations with very many points.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do you need to call before you can draw on a canvas?

    getContext("2d") returns the 2D rendering context, the object with all the drawing methods.
  2. 2. A canvas has no width or height attributes. How many pixels does its bitmap have?

    The default canvas size is 300 by 150 pixels.
  3. 3. Your canvas has width="200" but CSS makes it display 800px wide. What happens?

    CSS only changes the display size. The 200-pixel bitmap is stretched to fit. Set the width attribute to change the number of pixels.
  4. 4. Which call erases part of the canvas back to transparent?

    clearRect() makes the area fully transparent. Painting white only looks similar on a white background, and eraseRect() doesn't exist.

Summary

  • <canvas> is a pixel surface; you draw on it with JavaScript through canvas.getContext("2d").
  • The origin is the top-left corner, and y increases downward.
  • fillRect, strokeRect and clearRect draw and erase rectangles; fillStyle, strokeStyle, lineWidth and globalAlpha control how things look and persist until changed.
  • save() and restore() let you change settings temporarily.
  • The width/height attributes set the bitmap size (default 300 ร— 150); CSS only sets the display size, and setting width or height clears the canvas.
  • Put fallback content inside the element and add role="img" with a label, or an equivalent table, for meaningful graphics.

Next lesson: Drawing and Animating with Canvas.