Images & Media
HTML <canvas> element
Provides a bitmap drawing surface for scripting. Markup alone does not draw graphics; provide meaningful fallback content. Canvas draws pixels using a rendering context such as 2D. Its width and height attributes set bitmap dimensions; CSS dimensions change the display size. Provide a meaningful alternative for content and interaction that cannot be conveyed through pixels alone. It accepts global HTML attributes; individual global features may be inapplicable or restricted.
Formal Syntax & Structure
html syntaxhtml
<canvas width="300" height="150">Fallback</canvas>Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| width | non-negative integer | Defines element-specific width, commonly in CSS pixels. On images it can establish an intrinsic aspect ratio together with height; on canvas it sets the bitmap width. |
| height | non-negative integer | Sets an element-specific height, commonly in CSS pixels. On images, pair it with width matching the intrinsic aspect ratio to reserve layout space. It is not a CSS length with units. |
Return Value
HTMLCanvasElement
Content model: Transparent fallback content; follow restrictions for interactive descendants.
Working Example
Example Snippethtml
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <title>HTML example</title> </head> <body> <canvas id="chart" width="200" height="100">Sales chart: 20 books.</canvas> <script> const c = document.getElementById('chart').getContext('2d'); c.fillRect(10, 10, 80, 30); </script> </body></html>