The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Declare a canvas<canvas id="chart" width="640" height="360"> Chart data is listed below. </canvas>View examples
Get a 2D contextconst context = canvas.getContext('2d')View examples
Clear the bitmapcontext.clearRect(0, 0, canvas.width, canvas.height)View examples
Draw a filled rectanglecontext.fillRect(20, 20, 120, 60)View examples
Scale for device pixelscanvas.width = Math.round(cssWidth * devicePixelRatio)View examples
Declare responsive SVG<svg viewBox="0 0 100 100" role="img" aria-labelledby="title"> <title id="title">Chart</title> </svg>View examples
Draw a circle<circle cx="50" cy="50" r="40" fill="steelblue" />View examples
Draw an SVG path<path d="M10 90 L50 10 L90 90 Z" />View examples
Hide decorative SVG<svg aria-hidden="true" focusable="false">...</svg>View examples
Caption a graphic<figure> <svg role="img">...</svg> <figcaption>Quarterly revenue.</figcaption> </figure>View examples
Inherit text color<path fill="currentColor" d="..." />View examples

Canvas is an immediate-mode bitmap surface controlled by script; SVG is a retained vector document whose elements remain addressable. Use SVG for semantic diagrams and scalable interface graphics, canvas for dense or frequently redrawn pixels, and always provide an equivalent accessible representation of essential information.

Step by step

Detailed examples

01

Choose retained vectors or immediate pixels

SVG elements participate in a document tree and scale without raster blur, making them strong for icons, diagrams, and interactive shapes. Canvas retains only pixels after drawing, making it useful for dense plots, image processing, and game frames. Neither choice removes the need for textual alternatives.

Two graphic surfaces
<canvas id="heatmap" width="640" height="360">Heatmap values are available in the following table.</canvas>
<svg viewBox="0 0 120 40" role="img" aria-labelledby="logo-title">
  <title id="logo-title">CmdMemo mark</title>
  <circle cx="20" cy="20" r="16" /><text x="44" y="26">CmdMemo</text>
</svg>
Back to quick reference ↑
02

Reset drawing state intentionally

The 2D context is stateful: fill styles, transforms, clipping, and line settings persist. Use save and restore around local state changes. Clearing pixels does not reset the state or coordinate transform, and changing canvas width or height clears the bitmap entirely.

Draw with isolated state
const canvas = document.querySelector('#chart');
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.save();
context.fillStyle = '#2563eb';
context.fillRect(20, 20, 120, 60);
context.restore();
Back to quick reference ↑
03

Separate CSS size from bitmap resolution

Canvas width and height attributes define bitmap dimensions; CSS dimensions scale that bitmap. Match the backing store to the displayed size and devicePixelRatio for sharp output, then scale the context so drawing coordinates remain in CSS pixels. Recompute on meaningful size changes rather than every frame.

Prepare a sharp responsive canvas
const canvas = document.querySelector('#chart');
const cssWidth = canvas.clientWidth;
const cssHeight = canvas.clientHeight;
const ratio = window.devicePixelRatio || 1;
canvas.width = Math.round(cssWidth * ratio);
canvas.height = Math.round(cssHeight * ratio);
const context = canvas.getContext('2d');
context.scale(ratio, ratio);
Back to quick reference ↑
04

Use viewBox as the vector coordinate system

viewBox maps an internal rectangle into the SVG viewport and enables responsive scaling. SVG title can name a simple image; complex charts generally need nearby prose or a data table. Reuse unique IDs when aria-labelledby, gradients, masks, or clips reference elements.

Responsive bar chart icon
<svg viewBox="0 0 120 80" role="img" aria-labelledby="bars-title bars-desc">
  <title id="bars-title">Three rising bars</title>
  <desc id="bars-desc">Values are 30, 50, and 70.</desc>
  <rect x="10" y="50" width="25" height="20" /><rect x="47" y="30" width="25" height="40" /><rect x="84" y="10" width="25" height="60" />
</svg>
Back to quick reference ↑
05

Provide equivalent information, not just a label

A short title can name a simple icon; a complex visualization needs its conclusion and underlying values available in text or a table. Canvas fallback children are not a live mirror of pixels, so maintain equivalent DOM content yourself. Hide purely decorative graphics to avoid noise.

Chart with a data alternative
<figure>
  <canvas id="sales" width="600" height="300">Sales: Jan 10, Feb 14, Mar 18.</canvas>
  <figcaption>Sales increased from 10 to 18 units from January through March.</figcaption>
</figure>
Back to quick reference ↑
06

Style SVG while preserving reusable semantics

Inline SVG accepts CSS presentation properties and currentColor, which makes icons follow surrounding themes. Prefer classes and inherited values over repeated inline paint attributes. Vector geometry may not scale stroke widths as expected; use vector-effect deliberately when a constant visual stroke is required.

Themeable icon
<svg class="icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
  <path d="M4 12h16M12 4v16" fill="none" stroke="currentColor" stroke-width="2" />
</svg>
<style>.icon { inline-size: 1.25em; block-size: 1.25em; color: #2563eb; }</style>
Back to quick reference ↑

Local code tester

Try canvas and SVG

Compare a script-drawn bitmap with a scalable, themeable vector.

Runs in your browser
Preview

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. WHATWGHTML: The canvas elementhtml.spec.whatwg.org
  2. WHATWGCanvas 2D APIhtml.spec.whatwg.org
  3. World Wide Web ConsortiumSVG 2w3.org

Help us improve

Found a typo or missing example?

Tell us what would make this cheat sheet clearer, more complete, or more useful.

Share feedback