The <canvas> element is a blank rectangle of pixels that JavaScript can paint on. Charts, simple games, photo filters, signature pads and generative art are all built on it. Unlike HTML elements, shapes on a canvas are not objects you can select later; you draw them with commands, and to change anything you clear and redraw. This lesson covers drawing shapes and text, then a smooth animation with requestAnimationFrame.
In this lesson you will learn
- Getting the 2D drawing context
- Rectangles, lines, paths, circles and text
- Colours and styles:
fillStyle,strokeStyle,font - Animating with
requestAnimationFrame - Handling mouse clicks on a canvas
This lesson builds on the DOM and events.
Drawing Shapes and Text
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas drawing</title>
<style> body { margin: 8px; font-family: sans-serif; } canvas { border: 1px solid #cfd8dc; } </style>
</head>
<body>
<canvas id="c" width="420" height="200" role="img" aria-label="Bar chart of course enrolments"></canvas>
<script>
const canvas = document.getElementById("c");
const ctx = canvas.getContext("2d");
// Rectangles and text: a small bar chart
const data = [["HTML", 120], ["CSS", 95], ["JS", 150], ["SQL", 70]];
ctx.font = "13px sans-serif";
data.forEach(([label, value], i) => {
const x = 20 + i * 60, h = value, y = 170 - h;
ctx.fillStyle = "#1565c0";
ctx.fillRect(x, y, 40, h);
ctx.fillStyle = "#263238";
ctx.fillText(label, x + 4, 188);
ctx.fillText(value, x + 8, y - 4);
});
// Lines and paths
ctx.strokeStyle = "#90a4ae";
ctx.beginPath();
ctx.moveTo(10, 170);
ctx.lineTo(260, 170);
ctx.stroke();
// Circles with arc(), and a filled triangle path
ctx.fillStyle = "#ef6c00";
ctx.beginPath();
ctx.arc(320, 70, 40, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "#2e7d32";
ctx.beginPath();
ctx.moveTo(300, 180);
ctx.lineTo(400, 180);
ctx.lineTo(350, 120);
ctx.closePath();
ctx.fill();
</script>
</body>
</html>
Result
- The canvas size comes from its
widthandheightattributes, in pixels. The coordinate (0, 0) is the top-left corner, and y grows downwards. getContext("2d")returns the drawing object; every command goes through it.fillRect(x, y, width, height)draws a filled rectangle. The bars start at170 - hso they grow upwards from a baseline.fillTextwrites the labels.- Lines and custom shapes use a path:
beginPath(), thenmoveToandlineTo, thenstroke()for an outline orfill()for a solid shape.closePath()joins the last point back to the first. arc(x, y, radius, startAngle, endAngle)draws circles; angles are in radians, so a full circle isMath.PI * 2.role="img"andaria-labeldescribe the drawing for screen readers, because canvas content is otherwise invisible to them.
Animation and Interaction
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas animation</title>
<style> body { margin: 8px; font-family: sans-serif; } canvas { border: 1px solid #cfd8dc; display: block; } </style>
</head>
<body>
<canvas id="c" width="420" height="160" role="img" aria-label="Bouncing ball animation"></canvas>
<button id="toggle">Pause</button> <small>Click the canvas to add a ball.</small>
<script>
const canvas = document.getElementById("c");
const ctx = canvas.getContext("2d");
const balls = [{ x: 50, y: 50, dx: 2.5, dy: 2, r: 14, color: "#1565c0" }];
let running = !matchMedia("(prefers-reduced-motion: reduce)").matches;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // wipe the last frame
for (const b of balls) {
if (running) {
b.x += b.dx; b.y += b.dy;
if (b.x < b.r || b.x > canvas.width - b.r) b.dx *= -1; // bounce off walls
if (b.y < b.r || b.y > canvas.height - b.r) b.dy *= -1;
}
ctx.fillStyle = b.color;
ctx.beginPath();
ctx.arc(b.x, b.y, b.r, 0, Math.PI * 2);
ctx.fill();
}
requestAnimationFrame(draw); // ask for the next frame
}
requestAnimationFrame(draw);
canvas.addEventListener("click", e => {
const rect = canvas.getBoundingClientRect();
balls.push({ x: e.clientX - rect.left, y: e.clientY - rect.top,
dx: Math.random() * 4 - 2, dy: Math.random() * 4 - 2, r: 10,
color: `hsl(${Math.floor(Math.random() * 360)}, 70%, 45%)` });
});
const btn = document.getElementById("toggle");
btn.textContent = running ? "Pause" : "Play";
btn.addEventListener("click", () => {
running = !running;
btn.textContent = running ? "Pause" : "Play";
});
</script>
</body>
</html>
Result
- Animation is a loop: clear, update, draw.
clearRectwipes the previous frame, positions change bydxanddy, and each ball is drawn again. requestAnimationFrame(draw)asks the browser to calldrawbefore the next screen refresh, usually 60 times a second. It pauses automatically in background tabs, saving battery, whichsetIntervaldoes not.- Reversing
dxordywhen a ball reaches an edge makes it bounce. - Click positions arrive relative to the window, so
getBoundingClientRect()converts them to canvas coordinates. Click the canvas above to add balls. - The animation starts paused for visitors who prefer reduced motion, and the button lets anyone pause it.
Canvas Cheat Sheet
| Method or property | Purpose |
|---|---|
fillRect, strokeRect, clearRect | Rectangles |
beginPath, moveTo, lineTo, closePath | Build a path |
arc, ellipse, quadraticCurveTo | Curves and circles |
fill(), stroke() | Paint the current path |
fillStyle, strokeStyle, lineWidth | Colours and line thickness |
font, fillText, textAlign | Text |
drawImage(img, x, y) | Draw a picture or video frame |
save(), restore(), translate, rotate | Transformations |
Common Mistakes
- Sizing the canvas with CSS only, which stretches the pixels and makes drawings blurry. Set the
widthandheightattributes. - Forgetting
beginPath(), so every new fill redraws all earlier shapes too. - Using degrees in
arc; convert withdeg * Math.PI / 180. - Animating with
setIntervalinstead ofrequestAnimationFrame, which causes stutter and wastes battery.
Practice Exercises
Exercise 1. Draw a smiley face: a yellow circle with two eyes and a smile.
Show answer
ctx.fillStyle = "#fdd835";
ctx.beginPath(); ctx.arc(100, 100, 60, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = "#263238";
ctx.beginPath(); ctx.arc(80, 85, 7, 0, Math.PI * 2); ctx.fill();
ctx.beginPath(); ctx.arc(120, 85, 7, 0, Math.PI * 2); ctx.fill();
ctx.lineWidth = 4;
ctx.beginPath(); ctx.arc(100, 105, 30, 0.2 * Math.PI, 0.8 * Math.PI); ctx.stroke();
Exercise 2. Make a simple drawing pad: draw a line while the mouse button is held down.
Show answer
let drawing = false;
canvas.addEventListener("pointerdown", e => { drawing = true; ctx.beginPath(); ctx.moveTo(e.offsetX, e.offsetY); });
canvas.addEventListener("pointermove", e => { if (drawing) { ctx.lineTo(e.offsetX, e.offsetY); ctx.stroke(); } });
canvas.addEventListener("pointerup", () => { drawing = false; });
Pointer events work for mouse, pen and touch.
Frequently Asked Questions
Should I use canvas or SVG?
SVG keeps each shape as an element you can style, click and scale perfectly, which suits icons, diagrams and charts with few items. Canvas is faster for thousands of moving objects, games and pixel effects.
How do I make a canvas sharp on high-resolution screens?
Multiply the width and height attributes by window.devicePixelRatio, keep the CSS size the same, and call ctx.scale(ratio, ratio) before drawing.
Summary
- Get a 2D context with
getContext("2d")and draw with commands. - Paths build lines and shapes;
arcdraws circles in radians. - Animate by clearing, updating and drawing inside
requestAnimationFrame. - Describe canvas content with
aria-labelfor accessibility.
