Canvas

Updated · 8 min read
mediumES2026javascriptcanvasgraphicsanimation

The <canvas> element is a rectangle of pixels that JavaScript can draw on. Through its 2D rendering context, you draw shapes, lines, text and images by calling methods like fillRect, arc and fillText. Canvas is immediate mode: once something is drawn, it's just pixels; the canvas doesn't remember shapes, so to change the picture you clear it and draw again. That makes canvas fast for games, charts with thousands of points, image editing and visual effects, while SVG (next lesson) suits pictures made of a few objects you want to change individually.

In One Minute

  • Get a context: const ctx = canvas.getContext("2d").
  • Rectangles: fillRect, strokeRect, clearRect. Paths: beginPath, moveTo, lineTo, arc, then fill() or stroke().
  • Style with fillStyle, strokeStyle, lineWidth, font, textAlign.
  • Set the canvas's pixel size separately from its CSS size, and scale by devicePixelRatio for sharp drawing.
  • Canvas content is invisible to screen readers: always provide a text alternative.

The Canvas and Its Context

first-canvas.html
<canvas id="c" width="300" height="150"></canvas>
<script>
  const canvas = document.querySelector("#c");
  const ctx = canvas.getContext("2d", { willReadFrequently: true });

  ctx.fillStyle = "seagreen";
  ctx.fillRect(20, 20, 120, 60);

  ctx.strokeStyle = "navy";
  ctx.lineWidth = 4;
  ctx.strokeRect(160, 20, 120, 60);

  console.log(canvas.width, canvas.height);
  console.log(Array.from(ctx.getImageData(30, 30, 1, 1).data).join(","));
  console.log(Array.from(ctx.getImageData(5, 5, 1, 1).data).join(","));
</script>
Output
300 150
46,139,87,255
0,0,0,0

Explanation: the coordinate system starts at the top-left corner, with x growing to the right and y growing down. fillRect(x, y, width, height) paints a filled rectangle; strokeRect draws its outline. getImageData reads pixels back as red, green, blue and alpha values from 0 to 255: the pixel at (30, 30) is seagreen, and (5, 5) is still transparent black (alpha 0). The willReadFrequently option tells the browser this canvas will be read back often, so it keeps the pixels where reading is fast (Chrome prints a hint suggesting it otherwise).

MethodDraws
fillRect(x, y, w, h)A filled rectangle
strokeRect(x, y, w, h)A rectangle outline
clearRect(x, y, w, h)Erases to transparent
fillText(text, x, y) / strokeText(...)Text
drawImage(image, x, y, w?, h?)An image, video frame or another canvas
fill() / stroke()The current path

Paths

A path is a shape built from lines and curves, then filled or stroked:

paths.html
<canvas id="c" width="300" height="160"></canvas>
<script>
  const ctx = document.querySelector("#c").getContext("2d");

  ctx.beginPath();
  ctx.moveTo(20, 140);
  ctx.lineTo(80, 60);
  ctx.lineTo(140, 100);
  ctx.lineTo(200, 30);
  ctx.strokeStyle = "royalblue";
  ctx.lineWidth = 3;
  ctx.stroke();

  ctx.beginPath();
  ctx.arc(250, 80, 30, 0, Math.PI * 2);
  ctx.fillStyle = "orange";
  ctx.fill();

  console.log(ctx.isPointInPath(250, 80), ctx.isPointInPath(20, 20));
</script>
Output
true false
Path methodDoes
beginPath()Starts a new path (forget the previous one)
moveTo(x, y)Moves the pen without drawing
lineTo(x, y)Draws a straight line to a point
arc(x, y, radius, startAngle, endAngle)A circle or part of one (angles in radians)
quadraticCurveTo, bezierCurveToCurves
rect(x, y, w, h), roundRect(x, y, w, h, r)Rectangles as paths
closePath()Draws a line back to the start
isPointInPath(x, y)Tests whether a point is inside the current path (for clicks)

Text and Colors

text.html
<canvas id="c" width="320" height="120"></canvas>
<script>
  const ctx = document.querySelector("#c").getContext("2d");
  ctx.fillStyle = "#1a1d21";
  ctx.font = "bold 20px sans-serif";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillText("Total paid: $250", 160, 40);

  const gradient = ctx.createLinearGradient(0, 0, 320, 0);
  gradient.addColorStop(0, "seagreen");
  gradient.addColorStop(1, "gold");
  ctx.fillStyle = gradient;
  ctx.fillRect(20, 80, 280, 20);

  console.log(Math.round(ctx.measureText("Total paid: $250").width) > 100);
</script>
Output
true

font uses CSS font syntax. measureText returns the text's width, which you need for centering, wrapping and labels in charts. Colors accept any CSS color, gradients and patterns.

Sharp Drawing on High-Density Screens

The width and height attributes set how many pixels the canvas has; CSS sets how big it looks. On a phone or Retina screen, one CSS pixel is two or three physical pixels, so a canvas sized only with CSS looks blurry. Scale it:

hidpi.html
<canvas id="c" style="width: 300px; height: 150px"></canvas>
<script>
  function setupCanvas(canvas) {
    const ratio = window.devicePixelRatio || 1;
    const { width, height } = canvas.getBoundingClientRect();
    canvas.width = Math.round(width * ratio);
    canvas.height = Math.round(height * ratio);
    const ctx = canvas.getContext("2d");
    ctx.scale(ratio, ratio);
    return ctx;
  }
  const ctx = setupCanvas(document.querySelector("#c"));
  ctx.fillRect(10, 10, 50, 50);
  console.log(devicePixelRatio, document.querySelector("#c").width);
</script>
Output
1 300

The checker's screen has a ratio of 1; on a typical phone, the canvas would get 600 or 900 pixels across, and ctx.scale lets you keep drawing in CSS-pixel coordinates.

Images

drawImage draws an image, a video frame or another canvas. The image must be loaded first:

image.html
<canvas id="c" width="100" height="100"></canvas>
<script>
  const ctx = document.querySelector("#c").getContext("2d");
  const img = new Image();
  img.addEventListener("load", () => {
    ctx.drawImage(img, 0, 0, 100, 100);
    console.log("drawn:", img.naturalWidth, "x", img.naturalHeight, "scaled to 100 x 100");
  });
  img.src = "data:image/svg+xml," + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10" fill="red"/></svg>');
</script>
Output
drawn: 10 x 10 scaled to 100 x 100

Images from another origin without CORS permission still draw, but they taint the canvas: getImageData and toDataURL then throw a SecurityError, so pages can't read pixels of images they aren't allowed to see.

Simple Animation

Because canvas doesn't remember shapes, animation means: clear, update the state, draw, repeat, with requestAnimationFrame:

animate.html
<canvas id="c" width="300" height="60"></canvas>
<script>
  const canvas = document.querySelector("#c");
  const ctx = canvas.getContext("2d");
  const duration = 400;
  let start;

  function frame(now) {
    start ??= now;
    const t = Math.min((now - start) / duration, 1);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "seagreen";
    ctx.fillRect(0, 20, t * canvas.width, 20);
    if (t < 1) requestAnimationFrame(frame);
    else console.log("bar filled:", Array.from(ctx.getImageData(299, 30, 1, 1).data).slice(0, 3).join(","));
  }
  requestAnimationFrame(frame);
</script>
Output
bar filled: 46,139,87

Accessibility

Canvas output is a picture: screen readers can't read the shapes or text in it. Always provide the information another way:

accessible-canvas.html
<canvas id="chart" width="400" height="200" role="img"
        aria-label="Payments by grade: grade 9 $165, grade 11 $85, grade 12 $300"></canvas>
<!-- or: put a real table next to it, or inside <canvas> as fallback content -->

In Practice

The Fee Tracker draws a bar chart of totals by grade on a canvas, with labels, and an accessible description generated from the same data:

bar-chart.html
<canvas id="chart" width="360" height="200" role="img"></canvas>
<script>
  const data = [{ label: "Grade 9", total: 165 }, { label: "Grade 11", total: 85 }, { label: "Grade 12", total: 300 }];
  const canvas = document.querySelector("#chart");
  const ctx = canvas.getContext("2d");
  const max = Math.max(...data.map((d) => d.total));
  const barWidth = 70, gap = 40, base = 170, chartHeight = 140;

  ctx.font = "13px sans-serif";
  ctx.textAlign = "center";
  data.forEach((d, i) => {
    const h = (d.total / max) * chartHeight;
    const x = gap + i * (barWidth + gap);
    ctx.fillStyle = "seagreen";
    ctx.fillRect(x, base - h, barWidth, h);
    ctx.fillStyle = "#1a1d21";
    ctx.fillText(`$${d.total}`, x + barWidth / 2, base - h - 6);
    ctx.fillText(d.label, x + barWidth / 2, base + 18);
  });

  canvas.setAttribute("aria-label", "Payments by grade: " + data.map((d) => `${d.label} $${d.total}`).join(", "));
  console.log(canvas.getAttribute("aria-label"));
  console.log("tallest bar height:", chartHeight);
</script>
Output
Payments by grade: Grade 9 $165, Grade 11 $85, Grade 12 $300
tallest bar height: 140

Common Mistakes

Forgetting beginPath(). Previous shapes get redrawn with new styles.

Sizing the canvas only with CSS. The drawing is stretched and blurry. Set width and height (times devicePixelRatio).

Drawing an image before it loads. Nothing appears. Draw in the load handler (or await img.decode()).

No text alternative. Add role="img" and an aria-label, or a table of the same data.

Practice

Challenge: Draw a progress ring: a gray full circle, then an arc in seagreen covering 75% of the circle starting at the top, and log the arc's end angle in degrees.

Show solution
ring.html
<canvas id="c" width="120" height="120"></canvas>
<script>
  const ctx = document.querySelector("#c").getContext("2d");
  const progress = 0.75;
  const start = -Math.PI / 2;
  const end = start + progress * Math.PI * 2;

  ctx.lineWidth = 12;
  ctx.strokeStyle = "#ddd";
  ctx.beginPath();
  ctx.arc(60, 60, 45, 0, Math.PI * 2);
  ctx.stroke();

  ctx.strokeStyle = "seagreen";
  ctx.beginPath();
  ctx.arc(60, 60, 45, start, end);
  ctx.stroke();

  console.log(Math.round((end * 180) / Math.PI));
</script>
Output
180

Quick check: Canvas

3 questions
1Where is (0, 0) on a canvas?
2Why call beginPath() before drawing a new shape?
3How do you make canvas content accessible?

Key Takeaways

TaskCode
Contextcanvas.getContext("2d")
Filled rectanglectx.fillRect(x, y, w, h)
Circlectx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill()
Textctx.fillText("$250", x, y)
Clearctx.clearRect(0, 0, canvas.width, canvas.height)
AnimaterequestAnimationFrame(draw)

Was this tutorial helpful?

Lesson 88 of 139