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

    FeatureCanvasSVG
    TypePixel-based (bitmap)Vector-based (DOM nodes)
    ScalingGets blurry on zoomInfinitely sharp
    Best forGames, visualisations, effectsIcons, logos, diagrams
    InteractivityManual hit-testingNative DOM events per element
    PerformanceBetter with many objectsSlows with 100s of nodes

    1. Canvas Shapes & Colours

    Try it Yourself ยป
    Code Preview
    <!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

    Try it Yourself ยป
    Code Preview
    <!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

    Try it Yourself ยป
    Code Preview
    <!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

    Try it Yourself ยป
    Code Preview
    <!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/lineTo draw basic shapes
    • โœ… createLinearGradient creates smooth colour transitions
    • โœ… Mouse events + lineTo/stroke enable freehand drawing
    • โœ… requestAnimationFrame creates 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.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service