HTML Tutorial · HTML5 Features · Lesson 20 of 34

HTML Canvas

Draw shapes, text and simple charts with the canvas element and its 2D drawing API.

The canvas element

<canvas> is a blank bitmap that you draw on with JavaScript. It's used for charts, games, image editing and visual effects.

<canvas id="chart" width="320" height="160">Fallback text for browsers and screen readers</canvas>
  • width and height set the drawing size in pixels. Set them as attributes (CSS only stretches the bitmap).
  • Content between the tags is shown when canvas isn't supported, and can describe the image.

Drawing with the 2D context

Get a drawing context, then call drawing methods:

Rectangles, circles and linesTry it yourself
<canvas id="c" width="300" height="150" style="border:1px solid #ccc">A red square, a blue circle and a line</canvas>
<script>
  const ctx = document.getElementById("c").getContext("2d");
  ctx.fillStyle = "crimson";
  ctx.fillRect(20, 20, 80, 80);          // x, y, width, height

  ctx.fillStyle = "royalblue";
  ctx.beginPath();
  ctx.arc(170, 60, 40, 0, Math.PI * 2);  // centre x, y, radius, start and end angle
  ctx.fill();

  ctx.strokeStyle = "seagreen";
  ctx.lineWidth = 4;
  ctx.beginPath();
  ctx.moveTo(20, 130);
  ctx.lineTo(280, 130);
  ctx.stroke();
</script>
Method Draws
fillRect(x, y, w, h) a filled rectangle
beginPath(), arc(), fill() circles and arcs
moveTo(), lineTo(), stroke() lines
fillText(text, x, y) text

The origin (0, 0) is the top-left corner, and y grows downwards.

A bar chart

A small bar chartTry it yourself
<canvas id="chart" width="320" height="180">Sales by quarter: Q1 40, Q2 75, Q3 55, Q4 90</canvas>
<script>
  const sales = { Q1: 40, Q2: 75, Q3: 55, Q4: 90 };
  const ctx = document.getElementById("chart").getContext("2d");
  ctx.font = "14px sans-serif";
  Object.entries(sales).forEach(([label, value], i) => {
    const x = 30 + i * 70, barHeight = value * 1.4;
    ctx.fillStyle = "#4f46e5";
    ctx.fillRect(x, 150 - barHeight, 40, barHeight);
    ctx.fillStyle = "#111";
    ctx.fillText(label, x + 8, 170);
    ctx.fillText(value, x + 8, 145 - barHeight);
  });
</script>

Canvas or SVG?

A canvas is a picture: once drawn, shapes are just pixels. It's fast for many objects and animation, but shapes aren't in the DOM, so they can't be styled with CSS, clicked individually or read by screen readers. SVG (next page) keeps every shape as an element. Always give a canvas a text alternative.

Test yourself

Why should a canvas chart have fallback or alternative text?

  1. Canvas content is pixels, so screen readers can't read the drawn shapes
  2. Canvas doesn't render without it
  3. It makes drawing faster
  4. Browsers require it for the 2D context
Show answer

Answer: Canvas content is pixels, so screen readers can't read the drawn shapes

Unlike SVG, drawn shapes aren't elements; describe the content in fallback text or a nearby caption.