HTML5 Canvas Introduction

Beginner
⏱️ ~14 min
📚 Updated: Aug 2026
🎯 5 Examples
🚀 5 Try-it labs
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—a raster surface JavaScript paints pixel by pixel. You will understand what canvas is, add it to a page, draw your first shapes, compare canvas with SVG, and know where to go next in the topic index.

What is Canvas

Raster basics

Learn how a pixel-based bitmap surface differs from vector markup.

Markup + JS

<canvas> tag

Add a canvas element, then draw into it with a short script.

2D API

Context methods

Meet fillRect, strokeRect, paths, arcs, text, and clearRect.

Compare

Canvas vs SVG

Choose Canvas, SVG, or PNG/JPEG for the right job.

Examples

Hands-on labs

Practice five snippets with View Output and Try It Yourself.

Topic Index

Full roadmap

Jump from lines and rectangles to text, color, and transforms.

Introduction

HTML5’s <canvas> element provides a way to dynamically render graphics, charts, animations, and other visualizations directly within a web page. Unlike SVG, which stores shapes as DOM nodes, canvas is raster-based—it generates a pixel bitmap that you paint programmatically with JavaScript.

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 its new position rather than updating a single element, the way you would with SVG or regular DOM nodes.

The Canvas 2D API is powerful and flexible, letting you build interactive, dynamic content in the browser without plugins—from simple charts to full 2D games.

Why it matters?

Games, dashboards, and creative tools need to redraw thousands of pixels every frame without the overhead of DOM elements. Canvas gives you pixel-level control, high-performance animation, and image manipulation in a single, script-driven surface.

Key Highlights

Pixel-Level Control

Read and write individual pixels with getImageData for filters and effects.

Smooth Animation

Redraw the canvas each frame with requestAnimationFrame for 60fps 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 on top of pixels.

In short: add a <canvas> element, grab its 2D context with JavaScript, and call drawing methods to paint pixels—clearing and redrawing to animate.

📝 Basic Structure

Start with the HTML element itself. Always set explicit width and height attributes—the drawing resolution in pixels:

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

On its own, an empty canvas is just a blank rectangle. Add JavaScript to get the 2D rendering context and draw a filled rectangle:

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

Explanation

PieceRole
<canvas>Root element; width/height set the pixel drawing resolution
getContext('2d')Returns the CanvasRenderingContext2D object used for every draw call
fillStyleColor, gradient, or pattern used by the next fill operation
fillRect(x, y, w, h)Draws a filled rectangle at position (x, y) with size w × h

Continue to Try It Yourself (tryit=1) to edit the bare markup, or tryit=2 to edit the red-rectangle script live.

🛰️ Core Canvas API

The Canvas 2D API provides a wide range of methods for drawing shapes, paths, text, images, and more. Each links to its dedicated tutorial when one exists:

MethodWhat it doesTutorial
fillRect(x, y, w, h)Draws a filled rectangleDraw Rectangles
strokeRect(x, y, w, h)Draws the outline of a rectangleDraw Rectangles
clearRect(x, y, w, h)Clears a rectangular area (transparent)
beginPath() / moveTo() / lineTo()Starts a path and draws straight segmentsDraw Lines
arc(x, y, r, start, end)Draws a circular arcDraw Arc
quadraticCurveTo() / bezierCurveTo()Draws curved path segmentsQuadratic · Bezier
fillText(text, x, y)Draws filled text at a positionText
save() / restore()Pushes and pops the current style/transform stateStates
translate() / rotate() / scale()Moves, rotates, and scales the drawing originTransform
drawImage()Draws an image, video frame, or another canvasManipulating Images

⚡ 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();
Draw textctx.fillText('Hi', 10, 20);
Clear canvasctx.clearRect(0, 0, canvas.width, canvas.height);
Animation framerequestAnimationFrame(draw);

📋 Canvas vs SVG vs PNG/JPEG

All can display graphics, but they solve different problems.

Canvas
bitmap surface

Best for games, dense charts, particle effects, and pixel manipulation drawn with JavaScript. Scales cleanly only if redrawn.

SVG
vector markup

Best for icons, logos, diagrams, and UI illustrations that must stay sharp, styleable, and DOM-accessible.

PNG / JPEG
raster image

Best for photos, textures, and complex imagery baked into a fixed pixel grid.

Learn more in the SVG Introduction when you need scalable, DOM-accessible vector graphics.

Context

When to Use Canvas

Reach for canvas whenever your graphic must redraw fast, react to pixels, or simulate a real drawing surface.

  1. 2D games

    Sprites, tile maps, and HUDs that redraw every frame with the animation loop.

  2. Dense charts & data viz

    Thousands of data points render faster as pixels than as individual DOM/SVG nodes.

  3. Photo & pixel editors

    Crop, filter, and composite images with direct pixel access via getImageData.

  4. Creative & generative art

    Particle systems, signature pads, and whiteboards that draw freehand strokes.

  5. Not for scalable icons

    Simple logos and UI icons that must stay crisp at any size belong in SVG, not canvas.

Key benefit: canvas can redraw huge numbers of shapes every frame without the DOM overhead that vector or HTML-node approaches carry.

📚 Canvas Topic Index

Browse every Canvas tutorial on CodeToFun, grouped by learning path. Start with Draw Lines.

Core Drawing

Text & Composition

State & Styling

Color & Effects

Transforms

Examples Gallery

Five starter demos. Use View Output to preview here, or open Try It Yourself to edit and run live (?tryit=1 through 5).

📚 Getting Started

Start with the bare canvas tag, then draw a rectangle, shapes, text, and finally an animation.

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

How It Works

An empty canvas renders as a transparent box the size of its width and height attributes—nothing is drawn until JavaScript runs.

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

How It Works

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). Continue in the Draw Rectangles tutorial.

Example 3 — Filled and stroked shapes

Combine a semi-transparent rectangle, a stroked outline, and a filled circle in one drawing.

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

How It Works

Each shape sets its own fillStyle/strokeStyle before painting. The circle uses beginPath(), arc(), then fill() and stroke()—the same path pattern used throughout the Canvas API. See Draw Arc for more.

Example 4 — Text on canvas

Render a bold heading and a smaller subtitle with fillText.

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

How It Works

font accepts CSS-style font shorthand; fillText(text, x, y) paints the baseline at y. Learn alignment and stroke text in the Text tutorial.

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

How It Works

Each frame: clear old pixels with clearRect, update x, then draw again. requestAnimationFrame syncs the loop with the browser’s refresh rate (~60fps) for smooth motion.

Use Cases

Real-world places where canvas shows up every day on the web.

1. 2D Games

Sprites, tile maps, and physics loops running entirely in the browser.

Example: a platformer or puzzle game HUD.

2. Charts & Data Viz

Fast-rendering line, bar, and scatter charts with thousands of points.

Example: a Chart.js dashboard widget.

3. Photo Editors

Crop, filter, and composite images directly in the browser.

Example: an in-browser avatar cropper.

4. Drawing Apps & Whiteboards

Freehand strokes captured from mouse, touch, or pen events.

Example: a signature pad or collaborative whiteboard.

5. Particle Effects

Confetti, snow, fire, and other animated pixel effects.

Example: a celebratory confetti burst on a success page.

6. Custom UI Widgets

Gauges, sliders, and visualizations that HTML/CSS can’t easily express.

Example: a circular progress ring or color picker wheel.

Pro Tip: if the graphic redraws often or reacts to pixels, canvas usually beats SVG or plain DOM elements for performance.

Advantages

Why canvas is an excellent choice for dynamic, pixel-driven graphics.

  1. 1. Pixel-Level Control

    Read and write raw pixel data for filters, effects, and image processing.

  2. 2. High-Performance Animation

    Handles thousands of moving objects better than the same count of DOM/SVG nodes.

  3. 3. Rich Interactivity

    Mouse, touch, and keyboard events power drawing tools and games.

  4. 4. Image Manipulation

    drawImage and pixel access enable cropping, filters, and compositing.

  5. 5. WebGL Upgrade Path

    getContext('webgl') enables hardware-accelerated 3D on the same canvas element.

Pro Tip: keep drawing logic in small, reusable functions so games and charts stay easy to test and extend.

Usage Tips

Follow these practices for clean, performant canvas drawing.

  1. 1. Always set width and height attributes

    Size the canvas with HTML attributes, not CSS alone, to avoid a stretched, blurry bitmap.

  2. 2. Use requestAnimationFrame for animation

    It syncs with the browser’s refresh rate and pauses in background tabs, unlike setInterval.

  3. 3. Call clearRect before redrawing

    Clear the previous frame first, or old pixels smear into the new drawing.

  4. 4. Wrap related styles with save()/restore()

    Avoid one shape’s style or transform leaking into the next drawing call.

  5. 5. Handle devicePixelRatio for retina screens

    Scale the backing bitmap up and CSS size down for sharp lines on high-DPI displays.

Pro Tip: know basic JavaScript first—variables, functions, and document.getElementById—then add one drawing command and watch pixels appear immediately.

Common Pitfalls

Avoid these mistakes when canvas does not look or behave as expected.

  1. 1. Resizing with CSS only

    Setting width/height in CSS without matching HTML attributes stretches the bitmap and blurs drawings.

    → Set width/height attributes to the real pixel resolution you draw at.

  2. 2. Forgetting clearRect in animation

    Skipping the clear step each frame leaves a smeared trail of previous drawings.

    → Call ctx.clearRect(0, 0, canvas.width, canvas.height) at the top of the draw loop.

  3. 3. Expecting DOM hit-testing on shapes

    Canvas shapes are pixels, not elements—you cannot attach a click listener to a single drawn circle.

    → Compute hit-testing manually with pointer coordinates, or use isPointInPath().

  4. 4. Drawing before the DOM is ready

    Calling getElementById before the canvas exists returns null and throws on getContext.

    → Place the script after the canvas tag, or run it in a DOMContentLoaded handler.

  5. 5. Huge canvases hurting performance

    Very large bitmaps (especially with devicePixelRatio scaling) consume memory and slow every redraw.

    → Cap resolution to what the layout actually needs, and profile before scaling up further.

Pro Tip: if nothing appears, check that getContext('2d') did not return null, that fill/stroke colors are not transparent, and that coordinates fall inside the canvas bounds.

🧠 How Canvas Drawing Works

1

Get the 2D context

getContext('2d') returns the drawing API object for a canvas element.

Setup
2

Set styles

fillStyle, strokeStyle, lineWidth, and font configure the next draw call.

Style
3

Issue draw commands

Call fillRect, stroke, fillText, drawImage, and more.

Draw
=

Clear & redraw for animation

clearRect wipes the frame; repeat inside requestAnimationFrame for motion.

Important Notes

  • Canvas is raster-based; nothing is retained as elements—only pixels remain after each draw.
  • The coordinate origin is the top-left; x increases right, y increases down.
  • fillStyle paints interiors; strokeStyle paints outlines—set both before the matching draw call.
  • Set width/height attributes, not just CSS, to avoid a blurry, stretched canvas.
  • Canvas complements SVG rather than replacing it—many apps use both together.
  • Next step: draw your first stroke in the Canvas Draw Lines tutorial.

Quick Takeaway: get the 2D context, set styles, draw, and clear + redraw each frame for animation—canvas is JavaScript-driven pixels from start to finish.

Browser Support

The HTML5 Canvas 2D API has been supported in all major browsers for years, with no polyfill required for modern projects.

Canvas 2D

HTML5 Canvas

Useand getContext('2d') anywhere. Rectangles, paths, arcs, text, gradients, images, and requestAnimationFrame work consistently across Chrome, Firefox, Safari, Edge, and mobile browsers.

100% Modern browsers
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 Universal

Bottom line: Safe for production sites. WebGL (getContext('webgl')) is available for hardware-accelerated 3D on the same element when you need it.

Wrap Up

🎉 Conclusion

HTML5 Canvas is a versatile, powerful surface for dynamic graphics on the web. Its pixel-level control, animation performance, and scripting flexibility make it the right tool whenever SVG or plain CSS falls short.

By understanding getContext('2d') and the core drawing methods, you can build everything from simple charts to full 2D games—one fillRect or stroke call at a time.

Practice the five examples above, then continue to Canvas Draw Lines—the first Core Drawing topic in the sidebar.

Get the context, set styles, draw, and clear + redraw for animation. Compare with SVG when you need scalable, DOM-accessible graphics instead.

💡 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 small, 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
  • Expect click handlers on individual shapes—canvas has no per-shape DOM

Key Takeaways

Knowledge Unlocked

Five things to remember about Canvas

Draw pixel-perfect graphics the Canvas 2D way.

5
Core concepts
</> 02

getContext('2d')

Your drawing API

Structure
03

fillRect & stroke

Paint shapes and paths

Style
04

Animation Loop

clearRect + requestAnimationFrame

Motion
05

Next: Draw Lines

First Core Drawing topic

Path

❓ Frequently Asked Questions

Canvas is an HTML element that provides a bitmap drawing surface. JavaScript uses the Canvas 2D API (or WebGL) to render shapes, 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.
Start with Canvas Draw Lines at /canvas/draw-lines — the first Core Drawing topic in the sidebar — then practice rectangles, arcs, quadratic and bezier curves, and full paths before moving on to text, state, color, and transforms.

Did you Know? 🔊

Add a <canvas width="400" height="200"></canvas> element, then call canvas.getContext('2d') in JavaScript to draw shapes, text, and animations pixel by pixel. Canvas can export its pixels to an image with canvas.toDataURL()—handy for saving drawings or screenshots without a server round trip.

Continue to Canvas Draw Lines

Learn the first Core Drawing topic in the sidebar—beginPath, moveTo, lineTo, and stroke styles.

Draw Lines tutorial →

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.

9 people found this page helpful