HTML Canvas

Beginner
14 min read
Updated: Nov 2026
6 examples
getContext('2d')

Definition and Usage

The HTML <canvas> element adds a bitmap drawing surface to the page. You paint on it with JavaScript through the Canvas API—rectangles, paths, text, images, and frame-by-frame animation.

What does HTML provide?

HTML declares the surface: size (width / height), an id for script, and optional fallback text between the tags. Drawing itself is not markup—it is script calling methods on a 2D context.

How do you start drawing?

Select the element, then call getContext('2d'). That returns a CanvasRenderingContext2D object. Set styles (fillStyle, strokeStyle) and call methods like fillRect, arc, and fillText.

Canvas hub vs canvas tag page

This tutorial focuses on drawing graphics on an HTML page with the 2D Canvas API. Attribute-level detail for the element itself lives on HTML canvas Tag. For scalable vector markup, see HTML SVG.

Blank until script runs.

A canvas with no JavaScript is an empty rectangle. Always get the context and draw after the element exists in the DOM.

Size with attributes.

Set width and height on the element (defaults 300×150). Stretching only with CSS can blur or distort the bitmap.

2D vs WebGL.

This page uses getContext('2d'). The same element can also host WebGL for hardware-accelerated 3D—a separate API.

HTML Syntax

Place a canvas on the page, then draw with a short script:

HTML
<canvas id="board" width="400" height="200">
  Your browser does not support canvas.
</canvas>

<script>
  const canvas = document.getElementById("board");
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "#22c55e";
  ctx.fillRect(20, 20, 120, 80);
</script>

Core HTML Concepts

Pieces that make canvas drawing work on a page:

PieceRole
<canvas>Bitmap surface in the HTML document
width / heightDrawing buffer size in CSS pixels (not CSS layout alone)
getContext("2d")2D drawing API (CanvasRenderingContext2D)
Fallback contentText/HTML between tags for unsupported environments
CoordinatesOrigin (0, 0) at top-left; X right, Y down

Common 2D drawing methods

Method / propertyUse when
fillRect / strokeRectFilled or outlined rectangles
beginPath + arcCircles and arcs
fillStyle / strokeStyleColors before drawing
fillText / fontText on the bitmap
clearRectErase before the next animation frame
requestAnimationFrameSmooth redraw loops

Canvas vs SVG (for HTML authors)

CanvasSVG
ModelPixels (bitmap)Shapes in the DOM (vector)
How you drawJavaScript APIHTML/SVG markup (+ CSS)
Best forGames, filters, many moving objectsIcons, logos, accessible diagrams
Hit-testing shapesYou track them yourselfElements can receive events

How to Draw with Canvas in HTML

A practical workflow:

  1. Add <canvas id="…" width="…" height="…"> with fallback text.
  2. In script, document.getElementById(…) (or query after DOM ready).
  3. Call getContext("2d") and keep the context in a variable.
  4. Set styles (fillStyle, font, lineWidth).
  5. Draw shapes, paths, or text; clear and redraw for animation.
  6. For meaningful visuals, add aria-label or an HTML caption / data table.
GoalPattern
Static shapefillRect / arc once after load
Labeled chart titlefont + fillText
Moving spriteclearRect + redraw in requestAnimationFrame
Photo on canvasnew Image() + drawImage in onload

Live Preview

Change the fill color—the same <canvas> redraws with fillRect and fillText.

#3b82f6

Uses getContext("2d") on a real HTML canvas element.

Preview

HTML Examples

Six patterns: rectangle setup, circle, fill and stroke, text, animation, and a combined scene.

Example 1 — Setup and Rectangle

HTML
<canvas id="myCanvas" width="400" height="200"
  style="border:1px solid #ccc"></canvas>
<script>
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "#ef4444";
  ctx.fillRect(50, 50, 150, 100);
</script>
Try It Yourself

How It Works

  1. canvas creates a 400×200 drawing buffer.
  2. getContext("2d") unlocks drawing methods.
  3. fillStyle sets the paint color.
  4. fillRect places a filled rectangle at (50, 50).

Example 2 — Draw a Circle

JS
var ctx = document.getElementById("c").getContext("2d");
ctx.beginPath();
ctx.arc(150, 150, 60, 0, Math.PI * 2);
ctx.fillStyle = "#3b82f6";
ctx.fill();
Try It Yourself

How It Works

  1. beginPath starts a fresh path.
  2. arc defines a full circle (0 to 2π radians).
  3. fill paints the closed path.
  4. Center is (150, 150) with radius 60.

Example 3 — Fill and Stroke

JS
ctx.fillStyle = "#22c55e";
ctx.fillRect(80, 60, 200, 100);
ctx.strokeStyle = "#000";
ctx.lineWidth = 5;
ctx.strokeRect(80, 60, 200, 100);
Try It Yourself

How It Works

  1. fillStyle colors the interior.
  2. fillRect draws the filled body.
  3. strokeStyle and lineWidth style the outline.
  4. strokeRect draws the border on the same box.

Example 4 — Text on Canvas

JS
ctx.font = "30px Arial";
ctx.fillStyle = "#1e293b";
ctx.fillText("Hello, Canvas!", 40, 80);
Try It Yourself

How It Works

  1. font uses a CSS-like string.
  2. fillText paints filled glyphs.
  3. Y is the text baseline, not the top of the letters.
  4. Screen readers do not read this text—add HTML alternatives when it matters.

Example 5 — Simple Animation

JS
var x = 0;
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#f97316";
  ctx.fillRect(x, 40, 40, 40);
  x += 2;
  if (x > canvas.width) x = 0;
  requestAnimationFrame(draw);
}
draw();
Try It Yourself

How It Works

  1. clearRect wipes the previous frame.
  2. fillRect draws the square at the new x.
  3. x advances each frame and wraps at the edge.
  4. requestAnimationFrame schedules the next redraw.

Example 6 — Combined Scene

HTML
<canvas id="myCanvas" width="500" height="300"
  style="border:1px solid #ccc"></canvas>
<script>
  var ctx = document.getElementById("myCanvas").getContext("2d");

  ctx.fillStyle = "lightblue";
  ctx.fillRect(50, 50, 200, 100);

  ctx.font = "20px Arial";
  ctx.fillStyle = "black";
  ctx.fillText("Hello Canvas", 80, 110);

  ctx.beginPath();
  ctx.arc(380, 100, 50, 0, Math.PI * 2);
  ctx.fillStyle = "tomato";
  ctx.fill();
</script>
Try It Yourself

How It Works

  1. One context paints rectangle, text, and circle in order.
  2. Later fills override fillStyle for the next shape.
  3. HTML still only holds the blank surface + script.
  4. Try It opens the full editable scene.

Edge Cases & Pitfalls

Most canvas bugs are sizing, timing, or assuming the bitmap is accessible like HTML.

size

CSS size ≠ buffer size

Changing only CSS width/height scales the bitmap and can look blurry. Prefer HTML width/height (or set them in JS).

timing

Script before the element

If getElementById runs too early, you get null. Put the script after the canvas or wait for DOMContentLoaded.

path

Forgetting beginPath

Without a new path, strokes and fills can connect to leftover geometry from earlier draws.

anim

Not clearing frames

Animation without clearRect leaves trails. Clear (or redraw a background) each frame.

a11y

Pixels are not semantic

Screen readers do not understand drawn shapes. Use fallback text, aria-label, or a data table beside charts.

limits

Huge canvases

Browsers cap canvas size (often around a few thousand pixels per side). Oversized surfaces may stop drawing.

Browser Support

The canvas element and Canvas 2D API are Baseline HTML/JavaScript. getContext('2d'), basic shapes, text, and requestAnimationFrame work in all modern browsers.

✓ Baseline · Widely available

HTML canvas

Bitmap drawing with the 2D context works across current browsers worldwide.

100% canvas + 2D API
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 6+ · Legacy environments
Full support
Opera All modern versions
Full support
HTML canvas Universal

Bottom line: Add a sized canvas, getContext('2d'), draw with fillRect/arc/fillText, and clear between animation frames.

Key Takeaways

  • <canvas> is a blank bitmap; JavaScript paints it.
  • getContext("2d") is the starting API for 2D drawing.
  • Set width/height attributes so drawings stay sharp.
  • Tag details on /html/tags/canvas; vectors on /html/svg.

One line: Put a sized <canvas> in HTML, call getContext("2d"), then draw with the Canvas API.

Frequently Asked Questions

Canvas is an HTML element that provides a blank bitmap surface. You draw on it with JavaScript using a 2D context from getContext('2d')—shapes, text, images, and animations.
This tutorial teaches how to draw graphics on an HTML page (setup, shapes, styles, text, animation). The /html/tags/canvas page is the element reference for attributes, sizing, and fallback content.
Use canvas for games, particle effects, and pixel-heavy drawing. Use SVG for icons, logos, and diagrams that should stay sharp and stay in the DOM.
Nothing appears until script runs. Check that the element exists before getContext, that width/height are set, and that drawing calls actually run after the page loads.
CSS size and canvas buffer size must match. Prefer width and height attributes (or JS) over stretching with CSS alone, especially on high-DPI screens.
Drawn pixels are not semantic HTML. Put fallback text inside canvas, add aria-label when needed, and provide a real HTML alternative for important data.

Practice in the editor

Open a Try It demo and combine rectangles, text, and circles on one canvas.

Open Try It editor →

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.

8 people found this page helpful