Skip to main content

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.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

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.

Diagram
Loading diagramโ€ฆ

Canvas 2D API enables high-performance graphics and animations via JavaScript

Canvas Example

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>

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/9 done