Codectionary / Developer documentation / HTML

<canvas>

The <canvas> element provides a blank, resizable bitmap surface for drawing graphics, animations, and visualizations via JavaScript — typically using the Canvas 2D API or WebGL. Unlike SVG, canvas content is pixel-based rather than made of individually addressable DOM elements, which makes it well-suited for games, charts, and pixel-level image manipulation.

Syntax

<canvas id="myCanvas" width="400" height="300"></canvas>

Examples

Basic Canvas Setup

Creating a canvas and drawing a simple rectangle.

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #ccc;"></canvas>
<script>
  const ctx = document.getElementById("myCanvas").getContext("2d");
  ctx.fillStyle = "#3b82f6";
  ctx.fillRect(20, 20, 100, 80);
</script>

Drawing a Circle

Using canvas arc methods to draw shapes.

<canvas id="circleCanvas" width="200" height="200"></canvas>
<script>
  const ctx = document.getElementById("circleCanvas").getContext("2d");
  ctx.beginPath();
  ctx.arc(100, 100, 60, 0, Math.PI * 2);
  ctx.fillStyle = "#10b981";
  ctx.fill();
</script>

Fallback Content

Providing fallback content for browsers or users without canvas/script support.

<canvas id="chart" width="400" height="200">
  Your browser does not support canvas. Here is a summary: Sales grew 20% in Q2.
</canvas>

Attributes

  • width (number): The canvas width in pixels (default 300)
  • height (number): The canvas height in pixels (default 150)

Best practices

  • Set width/height as HTML attributes rather than CSS to avoid blurry, stretched rendering
  • Provide meaningful fallback content between the tags for cases where canvas or JavaScript is unavailable
  • For charts, diagrams, or icons that need to stay interactive and accessible as individual elements, consider SVG instead of canvas
  • Canvas content is not part of the accessibility tree by default — add ARIA attributes or fallback text for accessibility when the content is meaningful

At a glance

Purpose
Structure and meaning for web content
File extension
.html · .htm
Runs in
Web browsers
Usually used with
CSS and JavaScript

Specifications & further reading

Related HTML documentation