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.
Getting Started
👋 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.
Fundamentals
🤔 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.
Capabilities
🔑 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.
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.
Reference
🛰 Canvas API
The Canvas 2D API provides a wide range of methods for drawing shapes, paths, text, images, and more. Some essential methods include:
Method
What 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
Concepts
🧰 Core Building Blocks
As you continue learning canvas, these ideas form the foundation of every drawing program:
Concept
What it does
Rendering context
The CanvasRenderingContext2D object returned by getContext('2d')
Coordinate system
Origin (0, 0) is top-left; x increases right, y increases down
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);
}
Each frame: clear canvas → draw red square at x → move x → repeat
requestAnimationFrame syncs with the browser refresh rate (~60 fps)
🧠 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.
Compare
📋 Canvas vs SVG
Technology
Type
Best for
Canvas
Raster (pixels)
Games, animations, charts with many data points, image filters
SVG
Vector (DOM)
Icons, logos, diagrams, maps that scale to any size
CSS
Declarative styles
Page 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.
Recap
🎉 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.
Pro Tips
💡 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.