<canvas> is a bitmap drawing surface. JavaScript can draw into a 2D or other supported context. The drawn shapes are not ordinary DOM elements and do not automatically expose meaningful structure to accessibility tools.
Draw a rectangle
The script draws a blue rectangle on a 240-by-120 drawing surface. A visible description supplies the same information outside the bitmap.
HTML and CSS
HTML
<p id="description">
A blue rectangle starts 20 pixels from the left and 20 pixels from the top; it
is 120 pixels wide and 60 pixels tall.
</p>
<canvas
id="drawing"
width="240"
height="120"
role="img"
aria-labelledby="description"
>A blue rectangle on a blank background.</canvas
>
<script>
const context = document.querySelector('#drawing').getContext('2d'); if (context) { context.fillStyle = '#2563eb'; context.fillRect(20, 20, 120, 60); }
</script>
CSS
canvas {
max-width: 100%;
height: auto;
border: 1px solid #94a3b8;
}
Edit HTML or CSS to update the preview as you type. Copy code snippet copies the selected tab. Preview spacing and font defaults are not included.
Dimensions and content
Canvas needs an end tag. HTML width and height set its drawing coordinate space; defaults are 300 by 150. CSS-only resizing scales the bitmap and can blur or distort it. Assigning width or height again clears the drawing and resets context state.
Content inside canvas is fallback content. Supply readable information outside it as well, especially for charts or images whose information must be available without examining pixels. Interactive canvas experiences need real keyboard-accessible controls and equivalent semantics; a click handler on drawn shapes is not enough.
Exercise and alternatives
Change fillRect’s last two arguments to compare width and height. Then change the canvas width attribute and redraw. For static imagery use img; for a simple interface use native HTML. SVG is often useful when individual graphic objects need scalable structure.
Sources and browser support
MDN: canvas describes the syntax and links to the specification and compatibility data. Check individual values in that table when supporting older browsers.