HTML Canvas

Beginner
⏱️ 14 min read
📚 Updated: Jul 2026
🎯 6 Examples + 6 Try It
getContext('2d')

Introduction

The HTML <canvas> element is a powerful tool for drawing graphics with JavaScript. It provides a drawable region on your page where you can create 2D shapes, render text, draw images, and build animations.

Canvas is widely used for games, data visualizations, photo editors, and interactive web applications. This tutorial walks through setup, drawing basics, styling, transformations, and a complete working example.

What You’ll Learn

01

Setup

canvas + ctx.

02

Shapes

Rect & arc.

03

Colors

fill & stroke.

04

Text

fillText.

05

Transform

rotate, scale.

06

Animate

rAF loop.

What Is HTML Canvas?

The <canvas> element is part of HTML5. It renders a bitmap (grid of pixels) that you paint with JavaScript. Unlike static images, you can redraw the canvas every frame for animation or update charts when data changes.

Canvas is ideal when you need pixel-level control or thousands of moving objects. For logos and icons that scale cleanly, consider HTML SVG instead.

💡
Beginner Tip

Nothing appears on a canvas until you run JavaScript. The element only creates an empty drawing surface—getContext('2d') gives you the paintbrush.

Setting Up the Canvas

Define the canvas in HTML with width and height attributes (the internal pixel size):

html
<canvas id="myCanvas" width="400" height="300">
  Your browser does not support canvas.
</canvas>

Get the 2D rendering context in JavaScript:

js
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

Text between <canvas> tags is fallback content for very old browsers. See also the HTML canvas tag reference for all attributes.

Canvas Coordinates

The canvas uses a coordinate system where the top-left corner is (0, 0). X increases to the right; Y increases downward. When you draw at (50, 50), you place content 50 pixels from the left and 50 pixels from the top.

All drawing methods use these pixel coordinates unless you apply transformations (translate, scale, rotate) to the context.

Drawing Shapes

Canvas provides built-in methods for common shapes. Here are the two you will use most often:

Rectangles

fillRect(x, y, width, height) draws a filled rectangle. strokeRect draws only the outline.

js
ctx.fillStyle = '#FF0000';
ctx.fillRect(50, 50, 150, 100);

Circles

Use arc(x, y, radius, startAngle, endAngle) inside a path. Angles are in radians; a full circle runs from 0 to Math.PI * 2.

js
ctx.beginPath();
ctx.arc(150, 150, 50, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();

beginPath() starts a fresh path so previous shapes do not connect accidentally.

Working with Colors and Styles

Style drawings with context properties before calling draw methods:

  • fillStyle — interior color (names, hex, rgb).
  • strokeStyle — outline color.
  • lineWidth — stroke thickness in pixels.
js
ctx.fillStyle = 'green';
ctx.fillRect(100, 100, 200, 100);

ctx.strokeStyle = 'black';
ctx.lineWidth = 5;
ctx.strokeRect(100, 100, 200, 100);

Drawing Images

Load an image, then paint it onto the canvas with drawImage:

js
const img = new Image();
img.src = 'photo.jpg';
img.onload = function () {
  ctx.drawImage(img, 50, 50, 200, 150);
};

Drawing happens inside onload because the browser needs time to fetch the file. The last two numbers set width and height on the canvas.

Text on Canvas

Draw text with fillText (filled) or strokeText (outline). Set the font first, similar to CSS:

js
ctx.font = '30px Arial';
ctx.fillStyle = '#1e293b';
ctx.fillText('Hello, Canvas!', 50, 50);

The Y coordinate in fillText is the text baseline, not the top of the letters.

Canvas Transformations

Transform the coordinate system before drawing. Common methods:

Scaling

Change the size of subsequent drawings:

js
ctx.scale(2, 2);
ctx.fillRect(50, 50, 100, 50); /* draws 200×100 px */

Rotating

Rotate around the current origin (0, 0 by default):

js
ctx.rotate((Math.PI / 180) * 45); /* 45 degrees */
ctx.fillRect(100, 100, 100, 50);

Translating

Move the origin to a new point:

js
ctx.translate(100, 100);
ctx.fillRect(0, 0, 100, 50); /* appears at (100, 100) */

Wrap transforms in ctx.save() and ctx.restore() so later shapes use the default coordinate system.

Animation Basics

To animate, clear the canvas each frame and redraw at new positions. Use requestAnimationFrame for smooth, browser-optimized loops:

js
let x = 0;
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillRect(x, 40, 40, 40);
  x += 2;
  requestAnimationFrame(draw);
}
draw();

⚡ Quick Reference

TaskCode
Get contextcanvas.getContext('2d')
Filled rectanglectx.fillRect(x, y, w, h)
Circlectx.arc(x, y, r, 0, Math.PI*2); ctx.fill()
Fill colorctx.fillStyle = 'red'
Textctx.fillText('Hi', x, y)
Clear canvasctx.clearRect(0, 0, w, h)
Save / restore statectx.save(); ... ctx.restore();

Examples Gallery

Six examples from setup to animation. Each includes View Output and Try It Yourself.

📚 Getting Started

Create the canvas and draw your first shape.

Example 1 — Setup and Red Rectangle

html
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
  var ctx = document.getElementById('myCanvas').getContext('2d');
  ctx.fillStyle = '#ef4444';
  ctx.fillRect(50, 50, 150, 100);
</script>
Try It Yourself

How It Works

width and height on the element set the drawing buffer size. fillRect paints a solid rectangle.

Example 2 — Draw a Circle

js
ctx.beginPath();
ctx.arc(150, 150, 60, 0, Math.PI * 2);
ctx.fillStyle = '#3b82f6';
ctx.fill();
Try It Yourself

How It Works

arc center is (150, 150) with radius 60. Full circle uses radians 0 to .

🎨 Styling & Text

Colors, borders, and labels on the canvas.

Example 3 — Fill and Stroke

js
ctx.fillStyle = '#22c55e';
ctx.fillRect(100, 100, 200, 100);
ctx.strokeStyle = '#000';
ctx.lineWidth = 5;
ctx.strokeRect(100, 100, 200, 100);
Try It Yourself

How It Works

Fill runs first; stroke draws the border on top with lineWidth controlling thickness.

Example 4 — Text on Canvas

js
ctx.font = '30px Arial';
ctx.fillStyle = '#1e293b';
ctx.fillText('Hello, Canvas!', 50, 50);
Try It Yourself

How It Works

Set font before fillText. The string appears at coordinates (50, 50).

Example 5 — Simple Animation

A square moves horizontally using requestAnimationFrame.

js
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

Each frame clears the canvas and redraws the square at a new X position. When X passes the edge, it wraps to 0.

Example 6 — Complete Example

Rectangle, text, and circle on one canvas—no external images required:

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Canvas Example</title>
</head>
<body>
  <canvas id="myCanvas" width="500" height="300"></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>
</body>
</html>
Try It Yourself

How It Works

Combines techniques from this tutorial. The original reference used an external image URL—this version uses shapes only so it works offline in Try It.

Best Practices

✅ Do

  • Use save() and restore() around transforms
  • Set width/height attributes for pixel dimensions
  • Clear only the region that changed when optimizing animation
  • Provide fallback text inside <canvas>
  • Use requestAnimationFrame for smooth animation

❌ Don’t

  • Stretch canvas with CSS without adjusting internal resolution
  • Forget beginPath() between unrelated shapes
  • Draw images before onload fires
  • Rely on canvas alone for accessible data charts
  • Redraw the entire scene when a tiny part changed (at scale, optimize)

🚀 Common Use Cases

  • Games — sprites, collision, and frame loops.
  • Charts — bar, line, and pie visualizations (Chart.js uses canvas).
  • Image editing — filters and pixel manipulation.
  • Signatures — capture mouse/touch strokes.
  • Particle effects — fireworks, snow, confetti.
  • Video processing — draw video frames to canvas.

Universal Browser Support

Canvas 2D context is supported in all modern browsers. IE9+ had basic support; current Chrome, Firefox, Safari, and Edge fully support the API used in this tutorial.

Baseline · Since HTML

Canvas 2D API

Canvas 2D context is supported in all modern browsers. IE9+ had basic support; current Chrome, Firefox, Safari, and Edge fully support the API used in this tutorial.

98% 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 6+ · Legacy environments
Full support
Opera All modern versions
Full support
Canvas 2D API Excellent

Bottom line: Safe for production. Feature-detect with !!document.createElement('canvas').getContext if you need to support very old environments.

Conclusion

HTML Canvas is a versatile tool for rendering dynamic graphics in web applications. With methods for shapes, text, images, and transformations, it enables rich interactive experiences. Master the 2D context API to build games, charts, and visual tools.

Next, compare bitmap canvas drawing with vector graphics in HTML SVG, or dive into the canvas tag reference for every attribute.

Key Takeaways

🛠 02

getContext

2d API.

Setup
03

fillRect

Rectangles.

Draw
🔄 04

save/restore

State stack.

Transform
▶️ 05

rAF

Animate.

Motion

❓ Frequently Asked Questions

Canvas is an HTML element that provides a bitmap surface for drawing 2D graphics with JavaScript. You use methods like fillRect, arc, and fillText on a rendering context obtained via canvas.getContext('2d').
Canvas is pixel-based—you draw with JavaScript and cannot select individual shapes in the DOM. SVG is vector markup with DOM elements you can style and click. Use canvas for games and heavy animation; use SVG for icons and scalable illustrations.
Add <canvas id="myCanvas" width="400" height="300"></canvas>, then in JavaScript: var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d');. Call ctx.fillRect() or other drawing methods on ctx.
A blank canvas often means JavaScript ran before the element existed or getContext failed. Blurry drawings on retina screens happen when CSS width/height differs from canvas width/height attributes—set both or scale with devicePixelRatio.
ctx.save() pushes the current drawing state (styles, transforms) onto a stack. ctx.restore() pops it back. Use them around rotate/scale blocks so later drawings are not affected.
Canvas content is not exposed to screen readers by default. Provide fallback text inside <canvas> tags, duplicate important data in HTML, or use aria-label on the canvas. For interactive charts, consider SVG or supplement with a data table.
Did you know?

Canvas was introduced with HTML5 around 2004–2010 and quickly became the standard for in-browser games and charts. WebGL adds a webgl or webgl2 context for hardware-accelerated 3D on the same <canvas> element.

Draw on canvas in the editor

Open Try It, change fill colors and rectangle size, and see the bitmap update instantly.

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.

6 people found this page helpful