HTML <canvas> Tag

Beginner
⏱️ 8 min read
📚 Updated: Jun 2026
🎯 5 Examples
Graphics

What You’ll Learn

By the end of this tutorial, you’ll draw shapes, text, and simple animations on a canvas with JavaScript.

01

Canvas Syntax

Create a <canvas> element with pixel width and height.

02

2D Drawing API

Use getContext("2d") to draw rectangles, circles, and text.

03

canvas vs SVG

Choose bitmap canvas for games and charts; SVG for scalable vectors.

04

Animation

Animate shapes with requestAnimationFrame and clearRect.

05

Fallback Content

Provide inner text for browsers without canvas support.

06

Production Tips

Apply accessibility labels and sensible sizing practices.

What Is the <canvas> Tag?

The canvas element (<canvas>) is an HTML5 container for bitmap graphics. By itself it shows nothing useful—JavaScript uses getContext("2d") to draw rectangles, circles, text, images, and animated frames.

💡
JavaScript required

The canvas element is only a drawing surface. Shapes, text, and images appear only after JavaScript draws them with the Canvas 2D API.

Common uses include charts, games, image filters, drawing pads, data visualizations, and frame-by-frame animations.

📝 Syntax

Set width and height in pixels (numbers only, not percentages):

syntax.html
<!-- Basic canvas syntax -->
<canvas id="myCanvas" width="400" height="200"></canvas>

Syntax Rules

  • width and height attributes set the internal pixel grid—use numbers, not percentages.
  • Use CSS width to scale display size on screen without changing the buffer.
  • Place fallback text inside the element for unsupported browsers.
  • All drawing requires JavaScript after the canvas element is in the DOM.
fallback-syntax.html
<canvas id="myCanvas" width="400" height="200">
  Your browser does not support the HTML canvas element.
</canvas>

⚡ Quick Reference

Use CaseCode SnippetResult
Create canvas<canvas width="400" height="200"></canvas>Blank drawing surface
Get 2D contextcanvas.getContext("2d")Drawing API object
Draw rectanglectx.fillRect(x, y, w, h)Filled shape
Draw circlectx.arc(x, y, r, 0, 2*Math.PI)Filled arc/circle
Draw textctx.fillText("Hello", x, y)Text on canvas
Clear framectx.clearRect(0, 0, w, h)Animation reset

⚖️ <canvas> vs SVG

Choose the right technology based on your graphics needs:

Feature<canvas>SVG
TypeBitmap pixelsVector XML markup
DrawingJavaScript APIDOM elements
Best forGames, dynamic charts, filtersIcons, logos, accessible diagrams
AccessibilityNeeds aria-label + alternativesNative DOM accessibility

🧰 Attributes

Key <canvas> attributes for beginners:

width Required

Internal drawing buffer width in pixels. Must be a number, not a percentage.

width="400"
height Required

Internal drawing buffer height in pixels. Defines the coordinate grid size.

height="200"
id Global

Hook for JavaScript to select the canvas element with getElementById.

id="myCanvas"
aria-label A11y

Describe what the canvas shows for screen reader users.

aria-label="Sales chart Q1"
class Global

CSS hook for borders, display sizing, and layout.

class="chart-canvas"
Fallback content Optional

Text inside canvas shown when the browser does not support the element.

Canvas not supported.

Use CSS width to scale display size—do not use width="100%" as an HTML attribute.

🎨 Drawing on the Canvas

Get the 2D context, then call drawing methods:

draw-script.js
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 100, 80);

ctx.font = "20px sans-serif";
ctx.fillStyle = "black";
ctx.fillText("Hello, Canvas!", 170, 150);

Examples Gallery

Draw shapes, text, and animation on canvas with copy-ready code, live previews, and hands-on practice.

Live Preview

A canvas with a rectangle and text drawn by JavaScript:

Basic Canvas Element

Create a canvas with pixel dimensions and a simple drawn shape.

basic-canvas.html
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
  const ctx = document.getElementById("myCanvas").getContext("2d");
  ctx.fillStyle = "lightblue";
  ctx.fillRect(50, 50, 100, 100);
</script>
Try It Yourself

📚 Common Use Cases

Developers use <canvas> for charts, games, image filters, drawing pads, data visualizations, and frame-by-frame animations.

Rectangle and Text

Draw a filled rectangle and text label on the canvas.

rectangle-text.html
<script>
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "blue";
  ctx.fillRect(50, 50, 100, 80);
  ctx.font = "20px sans-serif";
  ctx.fillStyle = "black";
  ctx.fillText("Hello, Canvas!", 170, 150);
</script>
Try It Yourself

Draw a Circle

Use arc() with beginPath() to draw a circle.

draw-circle.html
<script>
  const ctx = canvas.getContext("2d");
  ctx.beginPath();
  ctx.arc(200, 100, 50, 0, 2 * Math.PI);
  ctx.fillStyle = "green";
  ctx.fill();
  ctx.closePath();
</script>
Try It Yourself

Simple Animation

Animate a shape with requestAnimationFrame and clearRect.

animation.html
<script>
  let x = 0;
  function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "red";
    ctx.fillRect(x, 50, 50, 50);
    x += 2;
    if (x > canvas.width) x = -50;
    requestAnimationFrame(animate);
  }
  animate();
</script>
Try It Yourself

Fallback Content

Place alternative text inside <canvas> for browsers without canvas support.

fallback.html
<canvas id="myCanvas" width="400" height="200">
  Your browser does not support the HTML canvas element.
</canvas>
Try It Yourself

Styling <canvas> with CSS

HTML attributes set the drawing buffer; CSS controls how the canvas appears on screen:

width / height Pixel buffer size
CSS width Display scaling
border Visual frame
max-width Responsive layout
canvas-styles.css
/* Responsive canvas display */
canvas {
  border: 1px solid #94a3b8;
  border-radius: 6px;
  background: #fff;
  max-width: 100%;
  height: auto;
}

Live styled canvas

♿ Accessibility

Canvas content is not directly accessible to screen readers:

  • Add aria-label — describe what the canvas shows.
  • Provide fallback text — inside the element for unsupported browsers.
  • Offer alternatives — a data table or text summary alongside charts.
  • Consider SVG — when accessibility and scalability matter more than pixels.

🧠 How <canvas> Works

1

HTML creates the surface

canvas with width and height allocates a blank pixel grid.

Markup
2

JavaScript gets 2D context

getContext("2d") returns the drawing API object.

Script
3

Draw shapes and pixels

Call fillRect, arc, fillText, or clear and redraw each animation frame.

Rendering
=

Dynamic graphics on the page

Charts, games, and visuals rendered in real time with JavaScript.

Universal Browser Support

The <canvas> element is supported in all modern browsers. Internet Explorer 9 and later also support it.

Baseline · Since HTML5

Dynamic graphics on every modern browser

From IE 9 to the latest mobile browsers — draw charts, games, and animations without plugins. Include fallback text for the rare unsupported environment.

100% Modern browser support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 9+ · Legacy
Full support
Opera All modern versions
Full support
<canvas> tag 100% supported

Bottom line: Ship canvas graphics with confidence. All modern browsers and IE 9+ support the element—just pair it with JavaScript and fallback text.

Conclusion

The <canvas> tag unlocks dynamic graphics on the web. Pair it with JavaScript’s 2D API for shapes, text, and animation.

Remember: set pixel width/height, provide fallback content, and add accessible descriptions for meaningful visuals.

💡 Best Practices

✅ Do

  • Set width and height in pixels
  • Use getContext("2d") for drawing
  • Include fallback text inside canvas
  • Add aria-label for accessibility

❌ Don’t

  • Use width="100%" as an HTML attribute
  • Expect graphics without JavaScript
  • Redraw the entire canvas unnecessarily
  • Use canvas when SVG is more appropriate

Key Takeaways

Knowledge Unlocked

Six truths every developer should know about <canvas>

Bookmark these before you ship — they’ll make every canvas graphic reliable and accessible.

6
Core concepts
02

JavaScript Required

Nothing appears until script calls the Canvas 2D API.

Essential
📝 03

Pixel Dimensions

width and height are numbers in pixels, not percentages.

Reference
🛠 04

2D Context

getContext("2d") unlocks rectangles, arcs, text, and images.

API
🚫 05

Fallback Content

Inner text appears when the browser cannot render canvas.

Resilience
🌐 06

Universal Support

Supported in all modern browsers and IE 9+. No polyfills required.

Compatibility

❓ Frequently Asked Questions

It provides a bitmap surface for drawing graphics, charts, games, and animations with JavaScript.
No. Canvas is only a container. All drawing requires JavaScript and the Canvas API.
Not as an HTML attribute. Use pixel values for width/height, then scale with CSS width: 100% if needed.
Canvas is pixel-based and script-driven. SVG is vector markup that scales and is more accessible.
Text inside <canvas> that appears when the browser cannot render the element.

Draw on Canvas

Practice rectangles, circles, and animation in the Try It editor.

Try canvas tag →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful