Skip to content

Canvas API

This lesson explains Canvas API with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 Canvas Overview

The HTML5 <canvas> element provides a drawable surface that allows developers to create graphics directly inside the browser using JavaScript. Unlike SVG, which uses DOM elements, Canvas is pixel-based, making it ideal for games, animations, charts, image processing, visualizations, and custom drawing applications.

Canvas itself is simply a container. All drawing operations are performed through the CanvasRenderingContext2D (2D Context) or WebGL context obtained from the canvas element.

Feature Description
Element <canvas>
Main Context CanvasRenderingContext2D
Rendering Type Pixel-based graphics
Languages HTML + JavaScript
Primary Uses Games, charts, animations, image editing, drawing
Browser Support Supported by all modern browsers

Basic Canvas Example

<canvas
  id="myCanvas"
  width="500"
  height="300">
  Your browser does not support HTML5 Canvas.
</canvas>

<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.fillStyle = "#2563eb";
ctx.fillRect(40, 40, 180, 100);
</script>

This example creates a canvas element, retrieves the 2D rendering context, and draws a blue rectangle using the fillRect() method.

Canvas Components

Component Purpose Example
Canvas Element Provides drawing area. <canvas>
2D Context Performs drawing operations. getContext("2d")
Canvas Width Sets drawing width. width="600"
Canvas Height Sets drawing height. height="400"
Drawing Methods Create shapes, text and images. fillRect()

Common Canvas Methods

Method Description Category
fillRect() Draws a filled rectangle. Shapes
strokeRect() Draws an outlined rectangle. Shapes
clearRect() Clears part of the canvas. Canvas
beginPath() Starts a new drawing path. Paths
moveTo() Moves drawing cursor. Paths
lineTo() Draws a line. Paths
arc() Draws circles and arcs. Shapes
fillText() Draws filled text. Text
strokeText() Draws outlined text. Text
drawImage() Draws an image. Images
save() Saves drawing state. State
restore() Restores drawing state. State

Canvas Features

Feature Description Common Uses
Shapes Draw rectangles, circles, lines, polygons. Games, diagrams, charts.
Text Render custom fonts and labels. Charts, dashboards.
Images Display and manipulate images. Photo editors, thumbnails.
Animation Create smooth animations. Games, interactive UI.
Transformations Rotate, translate, scale drawings. Games, visual effects.
Gradients Create color transitions. Modern graphics.
Patterns Repeat image textures. Backgrounds, textures.
Pixel Manipulation Access image pixels. Filters, editors.

Canvas Use Cases

Application How Canvas Is Used
Games Draw sprites, backgrounds, animations, and effects.
Charts Create line, bar, pie, and scatter charts.
Image Editors Crop, resize, filter, and annotate images.
Dashboards Display gauges, graphs, and visual metrics.
Digital Signatures Capture handwritten signatures.
Drawing Apps Create paint and sketch applications.
Data Visualization Render complex interactive graphics.
Animations Create smooth frame-based animations.

Canvas vs SVG

Feature Canvas SVG
Rendering Pixel-based Vector-based
Performance Excellent for many objects Better for fewer vector objects
DOM Elements No Yes
Accessibility Requires alternatives Better native accessibility
Best For Games, charts, animation Icons, logos, diagrams

Canvas Best Practices

  • Always check that the browser supports Canvas before drawing.
  • Separate drawing logic into reusable JavaScript functions.
  • Use requestAnimationFrame() for animations.
  • Clear the canvas before redrawing animated frames.
  • Optimize image sizes for better performance.
  • Scale the canvas for high-DPI displays.
  • Use semantic HTML when the content must be accessible.
  • Keep complex drawing calculations off the main thread when possible.

Common Canvas Mistakes

  • Forgetting to obtain the 2D context before drawing.
  • Drawing before the canvas exists in the DOM.
  • Using Canvas for simple UI that HTML and CSS can build more easily.
  • Ignoring accessibility requirements.
  • Not clearing the canvas during animations.
  • Loading images without waiting for the load event.
  • Using oversized images that reduce rendering performance.
  • Not considering device pixel ratio for retina displays.

Key Takeaways

  • Canvas is a pixel-based graphics API built into HTML5.
  • Drawing is performed using the 2D rendering context.
  • Canvas supports shapes, text, images, animations, and transformations.
  • It is widely used for games, charts, dashboards, and image editors.
  • Canvas offers excellent rendering performance for graphics-heavy applications.
  • Provide accessible alternatives because canvas content is not automatically exposed to assistive technologies.

Pro Tip

Choose Canvas when rendering thousands of dynamic objects or building animations and games. For icons, diagrams, scalable illustrations, and interactive vector graphics, SVG is often the better choice.