The canvas element provides a drawing surface for rendering graphics, charts, games, and dynamic visual content via JavaScript.
Description
The <canvas> element provides a bitmap drawing surface for JavaScript-driven graphics. VB styles canvases as block-level and responsive by default, with variants for borders, loading states, interactive cursors, and drawing modes.
When to Use
- Charts and graphs: Data visualization (Chart.js, D3, etc.)
- Games: 2D and 3D game rendering
- Image manipulation: Filters, cropping, compositing
- Animations: Complex animations beyond CSS capabilities
- Drawing tools: Signatures, sketches, annotation
When to Use Other Elements
- Use
<svg> for scalable, accessible vector graphics
- Use
<img> for static images
- Use CSS animations for simple, declarative motion
- Use
<video> for pre-recorded animated content
Attributes
| Attribute | Default | Effect |
width | 300 | Drawing buffer width in pixels, and the element's intrinsic width |
height | 150 | Drawing buffer height in pixels, and the element's intrinsic height |
Without the attributes a canvas is a 300×150 bitmap. Anything drawn outside the buffer is clipped, and CSS that sizes the element differently scales the bitmap rather than adding pixels (see Canvas Sizing).
Variants
VB provides variant classes for borders, loading placeholders, and cursor modes. The interactive demo below includes a coordinate tracker (hover) and a freehand drawing canvas (click and drag).
1
<canvas width="300" height="150"></canvas>
1
<canvas class="bordered" width="300" height="150"></canvas>
1
<canvas class="drawing" width="300" height="150"></canvas>
| Class | Effect |
| (default) | Block display, max-width 100% |
.bordered | Border + border-radius to define the canvas boundary |
.loading | Striped background pattern (placeholder before JS renders) |
.interactive | Crosshair cursor for click/hover interactions |
.drawing | Crosshair cursor + touch-action: none for freehand drawing |
.full | 100% container width, height from the aspect ratio of the buffer |
.fixed | Fixed height: 100% width, 400px tall |
Sizing classes stretch the bitmap. .full, .fixed and .canvas-responsive only change the CSS box; the drawing buffer keeps its width/height. Unless your script resizes the buffer to match (ResizeObserver + devicePixelRatio), drawings are scaled and look blurry or distorted.
Drawing Examples
Canvas requires JavaScript to render. These demos show shapes, a working bar chart with data labels, and a responsive canvas that reports its own dimensions.
<canvas id="my-canvas" width="400" height="150" role="img" aria-label="A filled rectangle, an outlined rectangle and a circle"></canvas>
123456789101112131415161718192021222324252627282930313233343536373839
const canvas = document.getElementById('my-canvas');const ctx = canvas.getContext('2d'); const probe = document.createElement('span');probe.hidden = true;document.body.append(probe);const token = (name) => { probe.style.color = `var(${name})`; return getComputedStyle(probe).color;}; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = token('--color-primary'); ctx.fillRect(20, 20, 150, 100); ctx.strokeStyle = token('--color-secondary'); ctx.lineWidth = 3; ctx.strokeRect(190, 20, 100, 100); ctx.beginPath(); ctx.arc(340, 70, 40, 0, Math.PI * 2); ctx.fillStyle = token('--color-success'); ctx.fill();} draw(); matchMedia('(prefers-color-scheme: dark)').addEventListener('change', draw);new MutationObserver(draw).observe(document.documentElement, { attributes: true, attributeFilter: ['data-mode', 'data-theme'],});
Never hard-code text or line colours such as #333 on a transparent canvas — they vanish on a dark surface. Read the theme tokens and redraw when the colour scheme changes, as above.
Responsive Canvas
Use .canvas-responsive to maintain aspect ratio while filling available width. The canvas is positioned absolutely inside the wrapper. Like the other sizing classes it sizes the box only — sync the drawing buffer in script (see Canvas Sizing).
123
<section class="canvas-responsive"> <canvas></canvas></section>
Custom Aspect Ratios
Override the default 16:9 ratio with a class in your stylesheet:
.canvas-responsive.square { aspect-ratio: 1; }.canvas-responsive.four-three { aspect-ratio: 4 / 3; }
123
<section class="canvas-responsive square" aria-label="Square chart"> <canvas></canvas></section>
Canvas Sizing
Canvas has two independent sizes: the element size (CSS) and the drawing buffer size (width/height attributes). For crisp rendering on high-density displays, set the buffer to the display size times devicePixelRatio.
.chart-canvas { inline-size: 300px; block-size: 200px;}
12
<canvas class="chart-canvas" width="600" height="400"></canvas>
Keeping the buffer in sync
When CSS sizes the canvas (.full, .fixed, .canvas-responsive), watch the box and resize the buffer:
123456789101112
const canvas = document.querySelector('canvas.full');const ctx = canvas.getContext('2d'); function resize() { const dpr = window.devicePixelRatio || 1; canvas.width = Math.round(canvas.clientWidth * dpr); canvas.height = Math.round(canvas.clientHeight * dpr); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); draw();} new ResizeObserver(resize).observe(canvas);
Accessibility
Canvas content is not accessible to screen readers by default. You must provide alternatives.
Fallback Content
Place content inside the canvas element. It renders when canvas is unsupported or scripting is disabled, and browsers expose it to screen readers even while the canvas is painting. Use it for data that deserves structure, like the values behind a chart.
12345678910
<canvas width="400" height="300"> <p>Bar chart showing quarterly sales:</p> <ul> <li>Q1: $45,000</li> <li>Q2: $52,000</li> <li>Q3: $48,000</li> <li>Q4: $61,000</li> </ul></canvas>
ARIA Labels
For simple informative graphics, use role="img" with aria-label. Pick one approach per canvas: role="img" makes the canvas a single image, so its children become presentational and any fallback content is no longer exposed to assistive technology. Use fallback content or role="img" + aria-label, not both.
123456
<canvas role="img" aria-label="Line chart showing website traffic increasing 25% over six months" width="400" height="300"></canvas>
Data Tables
For complex data visualizations, provide an accessible data table nearby:
1234567891011121314
<figure> <canvas id="sales-chart" width="600" height="400" role="img" aria-label="Annual sales by region, details in the table below"> </canvas> <figcaption> Annual sales by region. <a href="#sales-table">View data table</a> </figcaption></figure> <table id="sales-table"> </table>
Interactive Canvases
A canvas has no built-in keyboard support. For pointer-driven canvases, give the element tabindex="0", handle arrow keys (with Shift for larger steps) in a keydown listener, and mirror the state in real text, such as an <output> referenced by aria-describedby. The .interactive demo above uses this pattern. Freehand drawing cannot be done from a keyboard, so offer an alternative (a typed signature, an upload) where it matters.
Best Practices
- Always provide text alternatives for informative canvas content
- Use
role="img" and aria-label for simple graphics
- Provide data tables for charts and graphs
- Do not put
role="img" on interactive canvases — it tells assistive technology the canvas is a static picture
- Make interactive canvases keyboard operable
- Respect
prefers-reduced-motion for animated content
CSS Reference
| Selector | Properties |
canvas | display: block; max-inline-size: 100%; |
canvas.full | inline-size: 100%; block-size: auto; |
canvas.fixed (fixed height) | inline-size: 100%; block-size: 400px; |
canvas.interactive | cursor: crosshair; |
canvas.drawing | cursor: crosshair; touch-action: none; |
canvas.bordered | border; border-radius; |
canvas.loading | Diagonal stripe background pattern |
.canvas-responsive | position: relative; aspect-ratio: 16 / 9; |
Related
<svg> — Scalable vector graphics (often better for accessibility and resolution independence)
<img> — Static images
<figure> — Wrap canvas with captions for charts
<audio-visualizer> — VB's canvas-based audio visualization component