HTML5 Canvas Introduction

Beginner
⏱️ 14 min read
📚 Updated: Jul 2026
🎯 5 Examples
2D API · animation · games

What You’ll Learn

This page is a self-contained introduction to the HTML5 <canvas> element and its 2D drawing API. You will understand what canvas is, add it to a page, and draw your first shapes with JavaScript.

01

Introduction

What canvas adds.

02

What is Canvas

Raster graphics.

03

Key features

Dynamic rendering.

04

Basic usage

Markup + JS.

05

Canvas API

Core methods.

06

Animation

requestAnimationFrame.

👋 Introduction

HTML5 introduced the <canvas> element, which provides a way to dynamically render graphics, charts, animations, and other visualizations directly within a web page.

The Canvas API is powerful and flexible, allowing developers to create interactive and dynamic content in the browser without plugins. Combined with HTML for structure and CSS for layout, canvas opens the door to custom charts, games, and creative coding projects.

💡
Beginner tip

Know basic HTML and JavaScript first: variables, functions, and document.getElementById. Then add a canvas tag and one drawing command—you will see pixels appear immediately.

🤔 What is Canvas?

The <canvas> element is an HTML tag that acts as a container for graphics, allowing JavaScript to draw within it dynamically. Unlike SVG, which uses vector graphics stored as DOM nodes, canvas is raster-based—it generates pixel-based bitmaps that you paint programmatically.

Think of canvas as a blank sheet of graph paper: once you draw on it, the image is a grid of colored pixels. To move a shape, you typically clear the canvas and redraw everything in the new position rather than updating a single element.

🔑 Key Features of Canvas

  • Dynamic rendering — JavaScript generates graphics in real time as data or user input changes.
  • Pixel-level control — read and write individual pixels with getImageData for filters and effects.
  • Animation support — redraw the canvas each frame with requestAnimationFrame for smooth motion.
  • Interactivity — listen for mouse, touch, and keyboard events to build games and drawing tools.
  • Image manipulation — draw photos, crop regions, and apply compositing effects.
  • WebGL optiongetContext('webgl') enables hardware-accelerated 3D graphics.

🧐 Why Use Canvas?

Canvas is a powerful tool for creating dynamic and interactive content on the web. Here are common reasons to choose it:

  1. Dynamic graphics — build charts and visualizations that update when data changes.
  2. Performance — handle thousands of moving objects efficiently compared to many DOM elements.
  3. Animation — create smooth visual effects, transitions, and particle systems.
  4. Game development — render sprites, tile maps, and HUDs in 2D browser games.
  5. Creative tools — photo editors, whiteboards, and signature pads live entirely in the browser.

💡 Basic Usage of Canvas

To use the canvas element, add it to your HTML with explicit width and height attributes (the drawing resolution in pixels):

index.html
<canvas id="myCanvas" width="400" height="200"></canvas>
Try It Yourself

Then use JavaScript to get the 2D rendering context and draw:

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

// Draw a red rectangle
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);
Try It Yourself

We obtain a reference to the canvas element and its 2D rendering context (getContext('2d')). Then we set fillStyle and draw a filled rectangle with fillRect(x, y, width, height).

Online HTML Editor — paste HTML and script together to preview canvas drawings in the browser.

🛰 Canvas API

The Canvas 2D API provides a wide range of methods for drawing shapes, paths, text, images, and more. Some essential methods include:

MethodWhat it does
fillRect(x, y, w, h)Draws a filled rectangle
strokeRect(x, y, w, h)Draws the outline of a rectangle
clearRect(x, y, w, h)Clears a rectangular area (transparent)
beginPath()Starts a new path or resets the current path
moveTo(x, y)Moves the pen to coordinates without drawing
lineTo(x, y)Draws a line from the current point to (x, y)
arc(x, y, r, start, end)Draws a circular arc
fillText(text, x, y)Draws filled text at a position

🧰 Core Building Blocks

As you continue learning canvas, these ideas form the foundation of every drawing program:

ConceptWhat it does
Rendering contextThe CanvasRenderingContext2D object returned by getContext('2d')
Coordinate systemOrigin (0, 0) is top-left; x increases right, y increases down
Fill vs strokefillStyle / fillRect paint interiors; strokeStyle / stroke paint outlines
PathsCombine beginPath, moveTo, lineTo, and stroke or fill
State stacksave() and restore() preserve styles and transforms
Transformstranslate, rotate, and scale move the drawing origin
Animation loopClear, update positions, redraw each frame with requestAnimationFrame

⚡ Quick Reference

TaskCode snippet
Get contextconst ctx = canvas.getContext('2d');
Fill colorctx.fillStyle = '#2563eb';
Draw rectanglectx.fillRect(20, 20, 120, 80);
Draw linectx.moveTo(0,0); ctx.lineTo(100,50); ctx.stroke();
Clear canvasctx.clearRect(0, 0, canvas.width, canvas.height);
Animation framerequestAnimationFrame(draw);

Examples Gallery

Five starter demos. Use View Output to preview here, or open Try It Yourself to edit and run live in the browser.

Example 1 — Canvas markup only

The minimum HTML needed before any JavaScript runs.

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>My Canvas</title>
  </head>
  <body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
  </body>
</html>
Try It Yourself

Example 2 — Red filled rectangle

Classic first drawing: get the 2D context and call fillRect.

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Red Rectangle</title>
  </head>
  <body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
    <script>
      const canvas = document.getElementById('myCanvas');
      const ctx = canvas.getContext('2d');

      ctx.fillStyle = 'red';
      ctx.fillRect(10, 10, 100, 100);
    </script>
  </body>
</html>
Try It Yourself

Example 3 — Filled and stroked shapes

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Fill and Stroke</title>
  </head>
  <body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
    <script>
      const ctx = document.getElementById('myCanvas').getContext('2d');

      ctx.fillStyle = 'rgba(37, 99, 235, 0.35)';
      ctx.fillRect(40, 40, 140, 90);

      ctx.strokeStyle = '#0f172a';
      ctx.lineWidth = 4;
      ctx.strokeRect(30, 30, 160, 110);

      ctx.beginPath();
      ctx.arc(280, 100, 50, 0, Math.PI * 2);
      ctx.fillStyle = '#dc2626';
      ctx.fill();
      ctx.strokeStyle = '#991b1b';
      ctx.lineWidth = 3;
      ctx.stroke();
    </script>
  </body>
</html>
Try It Yourself

Example 4 — Text on canvas

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Canvas Text</title>
  </head>
  <body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
    <script>
      const ctx = document.getElementById('myCanvas').getContext('2d');

      ctx.fillStyle = '#0f172a';
      ctx.font = 'bold 28px system-ui, sans-serif';
      ctx.fillText('Hello, Canvas!', 40, 80);

      ctx.font = '16px Verdana, sans-serif';
      ctx.fillStyle = '#64748b';
      ctx.fillText('Draw labels, scores, and chart titles.', 40, 120);
    </script>
  </body>
</html>
Try It Yourself

Example 5 — Simple animation

A red square moves horizontally using requestAnimationFrame.

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Canvas Animation</title>
  </head>
  <body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
    <script>
      const canvas = document.getElementById('myCanvas');
      const ctx = canvas.getContext('2d');
      let x = 0;
      const dx = 2;

      function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        ctx.fillStyle = 'red';
        ctx.fillRect(x, 10, 50, 50);

        x += dx;
        if (x > canvas.width) {
          x = 0;
        }

        requestAnimationFrame(draw);
      }

      draw();
    </script>
  </body>
</html>
Try It Yourself

📄 Styling and Animation

Canvas graphics are styled through context properties—fillStyle, strokeStyle, lineWidth, globalAlpha, gradients, and patterns—rather than CSS rules on individual shapes. Animations work by clearing the canvas and redrawing objects in new positions each frame.

script.js
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = 'red';
  ctx.fillRect(x, 10, 50, 50);
  x += dx;
  if (x > canvas.width) x = 0;
  requestAnimationFrame(draw);
}
Try It Yourself

🧠 How it works?

In this pattern, we continuously redraw a red rectangle, moving it horizontally across the canvas. The animation loop is driven by requestAnimationFrame, which syncs with the browser’s refresh rate for smooth motion. Each frame: clear old pixels, update position, draw again.

📋 Canvas vs SVG

TechnologyTypeBest for
CanvasRaster (pixels)Games, animations, charts with many data points, image filters
SVGVector (DOM)Icons, logos, diagrams, maps that scale to any size
CSSDeclarative stylesPage layout, typography, transitions on HTML elements

🧠 How Canvas Drawing Works

1

Add <canvas>

HTML provides a bitmap surface with fixed width and height in pixels.

HTML
2

Get 2D context

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

JavaScript
3

Issue draw commands

Call fillRect, stroke, drawImage, etc.

Draw
=

Browser paints pixels

The canvas bitmap updates on screen; animations repeat each frame.

🎉 Conclusion

  • HTML5 <canvas> enables dynamic graphics, charts, and animations in the browser.
  • Canvas is raster-based; JavaScript draws pixel by pixel via the 2D rendering context.
  • Start with getContext('2d'), then use fillRect, paths, and text methods.
  • Animations clear and redraw each frame using requestAnimationFrame.
  • Canvas excels at games and data viz; SVG complements it for scalable vector graphics.
  • By leveraging the Canvas API and JavaScript, you can build everything from simple demos to complex interactive apps.

💡 Best Practices

✅ Do

  • Set width and height attributes on the canvas element
  • Use requestAnimationFrame for smooth animations
  • Call clearRect before redrawing animated scenes
  • Wrap related styles with save() and restore()
  • Test on mobile; handle devicePixelRatio for sharp retina displays
  • Keep drawing logic in reusable functions

❌ Don’t

  • Resize canvas only with CSS without updating width/height attributes
  • Draw thousands of DOM elements when canvas would perform better
  • Use canvas for text-heavy content screen readers must read
  • Forget to handle high-DPI screens on retina displays
  • Block the main thread with heavy computation every frame
  • Skip fallbacks or labels for accessibility-critical UI

❓ Frequently Asked Questions

Canvas is an HTML element that provides a bitmap drawing surface. JavaScript uses the Canvas 2D API (or WebGL) to render graphics, charts, animations, and games directly in the browser.
Yes. The canvas element alone is just an empty box. You need JavaScript to obtain a rendering context with getContext('2d') and call drawing methods like fillRect or stroke.
Neither is universally better. Canvas is raster-based and excels at animations, games, and pixel manipulation. SVG is vector-based and scales cleanly for icons, diagrams, and DOM-accessible graphics. Many projects use both.
Charts, data visualizations, photo editors, drawing apps, particle effects, 2D games, custom UI widgets, and interactive simulations. Libraries like Chart.js and Phaser build on canvas or WebGL.
Yes. Canvas has been supported in all major browsers for years. Always set explicit width and height attributes; CSS sizing alone stretches the bitmap and can blur drawings.
Create an HTML page with a canvas element, open it in a browser, and add a script that calls getContext('2d') then fillRect or stroke. Use the CodeToFun HTML Editor to experiment without installing anything.
Did you know?

Canvas can be used with other web technologies such as JavaScript and SVG to create interactive and dynamic web pages. Export a canvas to a PNG with canvas.toDataURL(), or overlay SVG icons on top of a canvas game HUD for crisp UI elements.

Try It Yourself

Edit any example from this page in the live Try It editor.

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.

12 people found this page helpful