Lesson 4 of 9
Canvas API for Drawing
The <canvas> element provides a JavaScript-based drawing surface for rendering 2D graphics - charts, animations, games, and image manipulation. Unlike SVG (which is retained-mode and DOM-based), Canvas is immediate-mode and pixel-based - you draw shapes with JavaScript commands and the result is a bitmap.
Canvas Basics
To use Canvas:
1. Create the element: <canvas id='chart' width='400' height='200'></canvas>
2. Get the 2D context: const ctx = canvas.getContext('2d');
3. Draw with JavaScript:
โข ctx.fillRect(x, y, width, height) - Filled rectangle
โข ctx.strokeRect(x, y, width, height) - Outlined rectangle
โข ctx.beginPath() + ctx.arc() + ctx.fill() - Circles
โข ctx.fillText('Hello', x, y) - Text
โข ctx.drawImage(img, x, y) - Images
Canvas vs SVG:
โข Canvas: Better for games, animations, many objects (pixel-based, not accessible)
โข SVG: Better for icons, logos, charts (vector-based, accessible, styleable with CSS)
IMPORTANT
Canvas content is NOT accessible - screen readers cannot read it. Provide fallback text inside the <canvas> tag for accessibility.
Canvas 2D API enables high-performance graphics and animations via JavaScript
Canvas Example
<!DOCTYPE html>
<html>
<body>
<canvas id="demo" width="300" height="200" style="border:1px solid #ddd;border-radius:8px"></canvas>
<script>
const ctx = document.getElementById('demo').getContext('2d');
// Sky
ctx.fillStyle = '#87CEEB';
ctx.fillRect(0, 0, 300, 120);
// Grass
ctx.fillStyle = '#4CAF50';
ctx.fillRect(0, 120, 300, 80);
// Sun
ctx.beginPath();
ctx.arc(250, 50, 30, 0, Math.PI * 2);
ctx.fillStyle = '#FFD700';
ctx.fill();
// Text
ctx.fillStyle = '#333';
ctx.font = '18px Arial';
ctx.fillText('Canvas Drawing!', 80, 180);
</script>
</body>
</html>Finished this lesson?