HTML & CSSMedium
What is <canvas>?
<canvas> is a bitmap drawing surface that you paint on with JavaScript, using the 2D context (getContext("2d")) or GPU APIs (WebGL, WebGPU). It is ideal for games, charts with thousands of points, image editing and visualizations, but its pixels have no DOM, so content is not accessible or searchable by default.
How it works
- Add
<canvas width="300" height="150">(the attributes set the drawing-buffer size). - Get a context:
const ctx = canvas.getContext("2d"). - Draw imperatively:
fillRect,arc,lineTo,fillText,drawImage. - To animate, clear and redraw each frame inside
requestAnimationFrame.
Canvas vs SVG
| Canvas | SVG | |
|---|---|---|
| Model | Immediate mode pixels | Retained DOM elements |
| Scales | Blurs when scaled | Crisp at any size |
| Many objects | Fast (10k+ points) | Slows with many nodes |
| Events/a11y | Manual hit-testing | Per-element events, accessible |
Gotchas
- HiDPI blur: multiply the buffer by
devicePixelRatioand scale the context. - CSS width/height stretch the bitmap; they do not resize the buffer.
- Drawing cross-origin images without CORS "taints" the canvas, blocking
toDataURL. - Provide a text alternative (fallback content inside the tag,
role="img"andaria-label).
Performance
OffscreenCanvas moves drawing into a Web Worker, keeping the main thread free.
Code example
html
1<canvas id="c" role="img" aria-label="Bouncing ball animation" style="width:300px;height:150px;border:2px solid #0b1020"></canvas>2<script>3 const canvas = document.getElementById("c");4 const dpr = window.devicePixelRatio || 1;5 canvas.width = 300 * dpr; // sharp on retina screens6 canvas.height = 150 * dpr;7 const ctx = canvas.getContext("2d");8 ctx.scale(dpr, dpr);910 let x = 40, y = 40, vx = 2.2, vy = 1.6;11 function frame() {12 ctx.clearRect(0, 0, 300, 150);13 ctx.fillStyle = "#2b4bff";14 ctx.beginPath();15 ctx.arc(x, y, 14, 0, Math.PI * 2);16 ctx.fill();17 ctx.fillStyle = "#0b1020";18 ctx.font = "14px system-ui";19 ctx.fillText(`x: ${x.toFixed(0)} y: ${y.toFixed(0)}`, 10, 140);20 x += vx; y += vy;21 if (x < 14 || x > 286) vx *= -1;22 if (y < 14 || y > 136) vy *= -1;23 requestAnimationFrame(frame);24 }25 requestAnimationFrame(frame);26</script>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.