HTML Canvas Essentials
Lesson 38 โข Advanced Track
What You'll Learn
- Draw rectangles, circles, triangles, and custom paths on <canvas>
- Apply fills, strokes, gradients, and text rendering
- Build an interactive drawing pad with colour picker and eraser
- Create smooth animations with requestAnimationFrame
- Draw a simple bar chart from data
๐ก Real-World Analogy
Canvas is like a digital whiteboard. You write drawing instructions in JavaScript ("draw a circle here, fill it green"), and the browser renders pixels. Unlike HTML elements, canvas drawings are not DOM nodes โ they're just pixels on a bitmap. Once drawn, they can't be individually selected or inspected.
Understanding Canvas
The <canvas> element provides a pixel-based drawing surface controlled entirely by JavaScript. You get a 2D rendering context via canvas.getContext('2d'), then use methods like fillRect(), arc(), and lineTo() to draw shapes.
Canvas is ideal for games, data visualisation, image manipulation, and real-time effects. For icons, logos, and diagrams, SVG is usually a better choice because it scales infinitely and elements are part of the DOM.
Canvas vs SVG
| Feature | Canvas | SVG |
|---|---|---|
| Type | Pixel-based (bitmap) | Vector-based (DOM nodes) |
| Scaling | Gets blurry on zoom | Infinitely sharp |
| Best for | Games, visualisations, effects | Icons, logos, diagrams |
| Interactivity | Manual hit-testing | Native DOM events per element |
| Performance | Better with many objects | Slows with 100s of nodes |
1. Canvas Shapes & Colours
<!DOCTYPE html>
<html><head><style>
body { font-family: system-ui, sans-serif; padding: 24px; }
canvas { border: 2px solid #ddd; border-radius: 8px; display: block; margin: 16px 0; background: #fafafa; }
h2 { color: #1565C0; }
</style></head><body>
<h1>Canvas: Shapes & Colours</h1>
<canvas id="shapes" width="500" height="300"></canvas>
<p>The canvas above shows rectangles, circles, triangles, text, and a gradient bar โ all drawn with JavaScript.</p>
<script>
const ctx = document.getElementById('
... Important: Set canvas dimensions via HTML attributes (<canvas width="500" height="300">), not CSS. CSS only stretches the bitmap โ the actual resolution stays at the HTML attribute values. Setting both CSS and attributes to different values creates blurry output.
2. Interactive Drawing Pad
<!DOCTYPE html>
<html><head><style>
body { font-family: system-ui, sans-serif; padding: 24px; }
canvas { border: 2px solid #ddd; border-radius: 8px; display: block; margin: 16px 0; background: white; cursor: crosshair; }
.controls { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin: 12px 0; }
.controls button { padding: 8px 16px; border: 2px solid #1976D2; background: transparent; color: #1976D2; border-radius: 6px; cursor: pointer; font-weight: 600; }
.controls button:hover
...3. Bouncing Ball Animation
<!DOCTYPE html>
<html><head><style>
body { font-family: system-ui, sans-serif; padding: 24px; }
canvas { border: 2px solid #ddd; border-radius: 8px; display: block; margin: 16px 0; background: #1a1a2e; }
.controls { display: flex; gap: 8px; margin: 8px 0; }
.controls button { padding: 8px 16px; border: 2px solid #64B5F6; background: transparent; color: #64B5F6; border-radius: 6px; cursor: pointer; font-weight: 600; }
</style></head><body>
<h1>Canvas Animation</h1>
<canvas id="anim" width="500" h
...4. Simple Bar Chart
<!DOCTYPE html>
<html><head><style>
body { font-family: system-ui, sans-serif; padding: 24px; }
canvas { border: 2px solid #ddd; border-radius: 8px; display: block; margin: 16px 0; background: white; }
h2 { color: #1565C0; }
</style></head><body>
<h1>Canvas: Simple Bar Chart</h1>
<canvas id="chart" width="500" height="300"></canvas>
<script>
const ctx = document.getElementById('chart').getContext('2d');
const data = [{label:'Jan',value:65},{label:'Feb',value:45},{label:'Mar',value:80},{label:'Ap
...When to Use This
- Games: Sprite rendering, collision detection, particle effects
- Data visualisation: Custom charts, graphs, and infographics
- Image manipulation: Filters, cropping, drawing on photos
- Signatures: Capturing handwritten signatures on forms
- NOT for: Simple icons, logos, or text โ use SVG or HTML instead
Common Mistakes
- Forgetting beginPath() โ Without it, all shapes connect into one continuous path. Call
beginPath()before each new shape. - CSS sizing vs attribute sizing โ Set width/height as HTML attributes, not CSS. CSS stretches the bitmap, creating blur.
- Using canvas for simple shapes โ If you just need an icon or logo, SVG is better (scales, accessible, styleable with CSS).
- Not clearing before animation frames โ Use
clearRect(0, 0, w, h)before redrawing. Or use semi-transparent fill for trail effects. - Drawing outside the canvas โ Canvas doesn't clip automatically in all cases. Calculate positions to stay within bounds.
- No accessibility โ Canvas content is invisible to screen readers. Add fallback text inside the
<canvas>element and use ARIA labels.
๐ Lesson Complete
- โ
getContext('2d')gives you the canvas drawing API - โ
fillRect,arc,moveTo/lineTodraw basic shapes - โ
createLinearGradientcreates smooth colour transitions - โ
Mouse events +
lineTo/strokeenable freehand drawing - โ
requestAnimationFramecreates smooth 60fps animations - โ Canvas is pixel-based; SVG is vector-based โ choose based on use case
- โ Always set dimensions via HTML attributes, not CSS
- โ
Add fallback content inside
<canvas>tags for accessibility
Sign up for free to track which lessons you've completed and get learning reminders.