The Canvas API

Published by Brayan K

The Canvas API lets you draw graphics pixel by pixel with JavaScript — shapes, lines, text, and images — by calling methods on a <canvas> element's 2D rendering context.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Separate the bitmap from the size of the page element

A canvas has a drawing buffer measured by its width and height attributes, and a layout box sized by CSS. Stretching the CSS box alone stretches the existing bitmap. Choose the logical drawing size and buffer resolution deliberately instead of assuming one CSS pixel always equals one buffer pixel.

const canvas = document.createElement("canvas");
canvas.width = 120;
canvas.height = 60;
// CSS displays the same bitmap at a larger layout size.
canvas.style.width = "240px";
canvas.style.height = "120px";
document.getElementById("app").append(canvas);
const context = canvas.getContext("2d");
if (!context) throw new Error("2D context unavailable");
context.fillStyle = "#2463eb";
context.fillRect(0, 0, 40, 30);
console.log(canvas.width, canvas.height);
console.log([...context.getImageData(10, 10, 1, 1).data].join(", "));

// ✅ Expected output:
// 120 60
// 36, 99, 235, 255

The pixel sample is inside a solid rectangle, avoiding font and edge antialiasing differences. It checks the drawing result, not just that a method was called. Canvas drawing is immediate bitmap state; there is no retained DOM element corresponding to this rectangle. DOM Manipulation owns ordinary element structure.

Resizing clears drawing state, while transforms can accumulate

const canvas = document.createElement("canvas");
canvas.width = 40; canvas.height = 40;
const context = canvas.getContext("2d");
context.fillStyle = "red";
context.scale(2, 2);
context.fillRect(0, 0, 10, 10);
canvas.width = canvas.width;
console.log(context.fillStyle, context.getTransform().a);
console.log(context.getImageData(5, 5, 1, 1).data[3]);

// ✅ Expected output:
// #000000 1
// 0
const context = document.createElement("canvas").getContext("2d");
context.scale(2, 2);
context.scale(2, 2);
console.log(context.getTransform().a);
context.setTransform(2, 0, 0, 2, 0, 0);
console.log(context.getTransform().a);

// ✅ Expected output:
// 4
// 2

A resize is not a harmless layout-only assignment, even when the new numeric width equals the old one. Reapply drawing state after resizing. For a high-density buffer, establish the transform from logical coordinates to actual buffer dimensions once for that render, rather than multiplying another scale on every update.

const canvas = document.createElement("canvas");
const width = 100, height = 50, ratio = 2;
canvas.width = width * ratio; canvas.height = height * ratio;
canvas.style.width = width + "px"; canvas.style.height = height + "px";
const context = canvas.getContext("2d");
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.fillStyle = "#2463eb";
context.fillRect(0, 0, 20, 20);
console.log(canvas.width, canvas.height);
console.log(context.getImageData(30, 10, 1, 1).data[3]);
console.log(context.getImageData(50, 10, 1, 1).data[3]);

// ✅ Expected output:
// 200 100
// 255
// 0

getImageData uses buffer coordinates, independent of the current transform. A device-pixel ratio can change between displays, and a very large buffer consumes memory. The brief bounds dimensions and accepts an explicit ratio so its output can be tested without depending on the current monitor.

The current path is not part of the saved drawing-state stack

const canvas = document.createElement("canvas");
canvas.width = 40; canvas.height = 20;
const context = canvas.getContext("2d");
context.fillStyle = "#2463eb";
context.beginPath(); context.rect(0, 0, 10, 10);
context.save();
context.fillStyle = "red";
context.beginPath(); context.rect(20, 0, 10, 10);
context.restore();
context.fill();
console.log(context.fillStyle);
console.log(context.getImageData(5, 5, 1, 1).data[3], context.getImageData(25, 5, 1, 1).data[3]);

// ✅ Expected output:
// #2463eb
// 0 255

save/restore manages drawing state such as styles, transforms and clipping. beginPath starts a new current path. Use it before an independent shape so later fills or strokes do not unexpectedly reuse earlier segments. fillRect draws directly and does not add a rectangle to the current path.

const canvas = document.createElement("canvas");
canvas.width = 20; canvas.height = 20;
const context = canvas.getContext("2d");
context.beginPath(); context.rect(0, 0, 10, 10); context.fill();
context.clearRect(0, 0, 20, 20);
console.log(context.getImageData(5, 5, 1, 1).data[3]);
context.fill();
console.log(context.getImageData(5, 5, 1, 1).data[3]);

// ✅ Expected output:
// 0
// 255

clearRect is also affected by the current transform and clipping region. If a render needs a complete fresh frame, reset the relevant state or establish a known transform and clipping policy before clearing. A canvas is stateful even when the JavaScript function that calls it looks small.

Map pointer coordinates through the displayed rectangle

const canvas = document.createElement("canvas");
canvas.width = 300; canvas.height = 150;
canvas.style.cssText = "width:150px;height:75px;border:0;padding:0";
document.getElementById("app").append(canvas);
const rectangle = canvas.getBoundingClientRect();
const clientX = rectangle.left + rectangle.width / 2;
const clientY = rectangle.top + rectangle.height / 2;
const x = (clientX - rectangle.left) * canvas.width / rectangle.width;
const y = (clientY - rectangle.top) * canvas.height / rectangle.height;
console.log(x, y);

// ✅ Expected output:
// 150 75

This formula assumes a positive-size, axis-aligned canvas without borders or padding, as shown. Rotated/skewed transforms or a border box need a more careful coordinate mapping. If your application draws in logical coordinates after scaling the context, map to those logical dimensions instead of blindly mixing them with buffer pixels.

Use actual pointer events for interaction and accessible HTML controls for actions. Painting a button-looking rectangle does not create a focusable button, an accessible name or keyboard behavior. Events owns input events; the surrounding DOM should carry readable labels and equivalent data.

Keep rendering, data and accessible meaning aligned

Retain the source data separately so you can redraw after resizing or state changes. A canvas bitmap is not the only copy of the model. For a chart, provide a text summary or table in the page and meaningful fallback text. This lesson’s brief supplies a concise label and fallback; a real complex chart may need a richer equivalent.

Drawing cross-origin image data without the required permission can taint a canvas and block readback or export. That restriction is not tested by these offline fixtures, which use only local solid shapes. Animation should use requestAnimationFrame with a deliberate time model; no frame-rate or physical-device performance claim is made here.

Guided exercise: establish a logical-to-buffer transform

Fill the literal hints. A logical 100 by 50 drawing uses a 200 by 100 buffer, and the transform is set explicitly instead of accumulated.

const canvas = document.createElement("canvas");
canvas.width = 100 * ___; // 👉 replace ___ with 2
canvas.height = 50 * 2;
const context = canvas.getContext("2d");
context.___(2, 0, 0, 2, 0, 0); // 👉 replace ___ with setTransform
context.fillStyle = "#2463eb";
context.fillRect(0, 0, 10, 10);
console.log(canvas.width, canvas.height, context.getTransform().___); // 👉 replace ___ with d

// ✅ Expected output:
// 200 100 2

Brief: draw bounded bars from validated values

Implement drawBars(canvas, values, width = 300, height = 150, ratio = 1). Accept an HTMLCanvasElement and a dense array of 1–12 finite Numbers from 0 through 100. Accept integer logical width 100–600, height 100–400 and a finite ratio from 1 through 3. Validate everything before changing the canvas.

Own this canvas’s bitmap and CSS size. Set buffer dimensions to the ceiling of logical size times ratio, and set the transform from the actual resulting buffer dimensions. Draw a white background, 12-unit padding, 4-unit gaps and blue bars whose heights represent the values on a fixed 0–100 scale. Zero must draw no bar area.

Return a frozen geometry report with a frozen array of frozen bar records. Set a role, descriptive aria-label and matching fallback text from the selected data. Do not mutate the values array or accumulate transforms across redraws. The function owns drawing only; external controls, richer tables and resize observation belong to its caller.

function drawBars(canvas, values, width = 300, height = 150, ratio = 1) {
  if (!(canvas instanceof HTMLCanvasElement)) throw new TypeError("canvas required");
  if (!Array.isArray(values) || values.length < 1 || values.length > 12) throw new TypeError("expected 1 to 12 values");
  const copied = [];
  for (let i = 0; i < values.length; i++) {
    if (!Object.hasOwn(values, i) || typeof values[i] !== "number" ||
        !Number.isFinite(values[i]) || values[i] < 0 || values[i] > 100) throw new TypeError("invalid value");
    copied.push(values[i]);
  }
  if (!Number.isInteger(width) || width < 100 || width > 600 ||
      !Number.isInteger(height) || height < 100 || height > 400 ||
      typeof ratio !== "number" || !Number.isFinite(ratio) || ratio < 1 || ratio > 3) {
    throw new RangeError("invalid drawing size");
  }
  const context = canvas.getContext("2d");
  if (!context) throw new Error("2D context unavailable");
  canvas.width = Math.ceil(width * ratio);
  canvas.height = Math.ceil(height * ratio);
  canvas.style.width = width + "px";
  canvas.style.height = height + "px";
  context.setTransform(canvas.width / width, 0, 0, canvas.height / height, 0, 0);
  context.fillStyle = "#ffffff";
  context.fillRect(0, 0, width, height);
  const padding = 12, gap = 4;
  const barWidth = (width - padding * 2 - gap * (copied.length - 1)) / copied.length;
  const bars = copied.map((value, index) => {
    const barHeight = (height - padding * 2) * value / 100;
    const bar = { value, x: padding + index * (barWidth + gap), y: height - padding - barHeight, width: barWidth, height: barHeight };
    context.fillStyle = "#2463eb";
    context.fillRect(bar.x, bar.y, bar.width, bar.height);
    return Object.freeze(bar);
  });
  const summary = "Bar values: " + copied.join(", ");
  canvas.setAttribute("role", "img");
  canvas.setAttribute("aria-label", summary);
  canvas.textContent = summary;
  return Object.freeze({
    width, height, pixelWidth: canvas.width, pixelHeight: canvas.height,
    bars: Object.freeze(bars)
  });
}
const canvas = document.createElement("canvas");
document.getElementById("app").append(canvas);
const values = [0, 50, 100];
const report = drawBars(canvas, values, 300, 150, 2);
const context = canvas.getContext("2d");
const middle = report.bars[1];
const sample = context.getImageData(Math.floor((middle.x + middle.width / 2) * 2), Math.floor((middle.y + middle.height / 2) * 2), 1, 1).data;
console.log(report.pixelWidth, report.pixelHeight, report.bars.map(bar => bar.height).join(", "));
console.log([...sample].join(", "));
console.log(canvas.getAttribute("aria-label"), Object.isFrozen(report.bars));
console.log(JSON.stringify(values));
drawBars(canvas, [100], 300, 150, 2);
console.log(context.getTransform().a);

// ✅ Expected output:
// 600 300 0, 63, 126
// 36, 99, 235, 255
// Bar values: 0, 50, 100 true
// [0,50,100]
// 2

Practice quiz

What does this complete program print? const canvas=document.createElement("canvas");canvas.width=100;canvas.style.width="200px";console.log(canvas.width);

  • 100
  • 200
  • 300
  • undefined

Answer: 100. CSS display size does not change the buffer width attribute.

What happens when canvas.width is assigned, even to its existing value?

  • Only the CSS layout changes
  • The bitmap and context state reset
  • The current drawing is scaled without clearing
  • Nothing can change

Answer: The bitmap and context state reset. Changing the buffer width resets its bitmap and rendering state.

What does this complete program print? const context=document.createElement("canvas").getContext("2d");context.scale(2,2);context.scale(2,2);console.log(context.getTransform().a);

  • 2
  • 1
  • 4
  • 0

Answer: 4. Scale operations multiply the existing transform.

Which operation starts a new current path?

  • save()
  • restore()
  • clearRect()
  • beginPath()

Answer: beginPath(). The current path is managed separately from the saved drawing-state stack.

What does this complete program print? const context=document.createElement("canvas").getContext("2d");context.fillStyle="red";context.save();context.fillStyle="blue";context.restore();console.log(context.fillStyle);

  • #ff0000
  • #0000ff
  • red,blue
  • #000000

Answer: #ff0000. The saved drawing state restores the previous fill style.

Which coordinates does getImageData use?

  • CSS layout coordinates
  • Drawing-buffer coordinates
  • Only coordinates before the last resize
  • The browser window’s screen coordinates

Answer: Drawing-buffer coordinates. Pixel readback uses the bitmap coordinate space rather than the current drawing transform.

What does this complete program print? const canvas=document.createElement("canvas");canvas.width=20;canvas.height=20;const context=canvas.getContext("2d");context.fillRect(0,0,10,10);context.clearRect(0,0,20,20);console.log(context.getImageData(5,5,1,1).data[3]);

  • 255
  • 1
  • 0
  • undefined

Answer: 0. The cleared pixel is transparent.

What makes a canvas chart understandable beyond its pixels?

  • Only a larger bitmap
  • Only a higher frame rate
  • Only a CSS border
  • Equivalent text/data and accessible interaction controls

Answer: Equivalent text/data and accessible interaction controls. The bitmap alone does not provide semantic structure or keyboard interaction.

Continue this course

Related lessons