← Back to Chapters

Canvas and SVG in HTML

? Canvas and SVG in HTML

⚡ Quick Overview

Both Canvas and SVG are used to draw graphics on the web, but they work in very different ways. Canvas is a bitmap you paint with JavaScript – great for fast-changing scenes such as games, particles, or big animated charts. SVG is vector markup that becomes real DOM elements – perfect for sharp, scalable, and interactive diagrams, icons, and maps.

Choosing between Canvas and SVG depends on what you care about more: raw performance with many drawing operations (Canvas) or crisp scaling and easy interactivity through the DOM and CSS (SVG).

? Key Concepts

?️ Canvas

  • Bitmap-based drawing surface accessed via JavaScript (2D or WebGL context).
  • Once drawn, shapes are “baked in” – Canvas does not remember individual objects.
  • Great for games, particle systems, many data points, and image processing.
  • Interactivity requires manual hit-testing (you compute what was clicked).
  • Can look blurry when scaled; fix with devicePixelRatio-aware rendering.

? SVG

  • Vector-based graphics written in XML / HTML syntax.
  • Each shape (<rect>, <circle>, etc.) is a DOM node.
  • Styles can be controlled with CSS and animated with CSS or JavaScript.
  • Interactivity is easy: attach events directly to shapes.
  • Scales crisply at any zoom level; ideal for logos, icons, and diagrams.

? Syntax & Theory

The <canvas> element itself is just a pixel surface. All actual drawing (lines, shapes, images) happens through a JavaScript drawing context:

? View Basic Canvas & SVG Syntax
<!-- Canvas: bitmap drawing surface -->
<canvas id="myCanvas" width="300" height="200">Fallback text</canvas>

<!-- SVG: vector graphics in the DOM -->
<svg viewBox="0 0 300 200" xmlns="http://www.w3.org/2000/svg">
  <rect x="50" y="50" width="200" height="100" fill="blue" />
</svg>

Canvas drawing is imperative (step-by-step drawing commands). SVG is declarative (you describe shapes and let the browser render them).

? Code Example: Canvas vs SVG Basics

? View Code Example
<!-- Canvas: draw a blue rectangle with high-DPI fix -->
<canvas id="c" width="300" height="200">Canvas fallback text</canvas>
<script>
  function setupCanvas(canvas, cssW, cssH){
    const ratio = Math.max(1, Math.floor(window.devicePixelRatio || 1));
    canvas.style.width = cssW + 'px';
    canvas.style.height = cssH + 'px';
    canvas.width = cssW * ratio;
    canvas.height = cssH * ratio;
    const ctx = canvas.getContext('2d');
    ctx.setTransform(ratio, 0, 0, ratio, 0, 0); // scale drawing ops
    return ctx;
  }
  const ctx = setupCanvas(document.getElementById('c'), 300, 200);
  ctx.fillStyle = 'blue';
  ctx.fillRect(50, 50, 200, 100);
</script>

<!-- SVG: same rectangle, crisp at any zoom -->
<svg viewBox="0 0 300 200" class="svg-responsive" aria-label="SVG Blue Rectangle"
     role="img" xmlns="http://www.w3.org/2000/svg">
  <rect x="50" y="50" width="200" height="100" fill="blue" />
</svg>

? Live Output / Explanation

?️ Canvas vs SVG Demo

Below, the Canvas side draws a rectangle and an animated bouncing ball using JavaScript. The SVG side shows a static rectangle that you can interact with as a normal DOM element.

Tip: Click inside the blue shape. In SVG, the rectangle gets the click directly. In Canvas, your code must calculate whether the click was inside the drawn area.

? Interactivity Differences (Demo Code)

? View Interactivity Code
// Canvas: manual hit-test
canvas.addEventListener('click', (e) => {
  const r = canvas.getBoundingClientRect();
  const x = e.clientX - r.left;
  const y = e.clientY - r.top;
  if (x >= 50 && x <= 250 && y >= 50 && y <= 150) {
    alert('Canvas rect clicked');
  }
});

// SVG: attach directly to the shape
document.getElementById('svgRect').addEventListener('click', () => {
  alert('SVG rect clicked');
});

? When to Choose Canvas or SVG

  • Choose Canvas for: games, particle systems, image filters, charts with thousands of points, or heavy animations where you redraw the whole scene each frame.
  • Choose SVG for: UI icons, logos, diagrams/flowcharts, maps with clickable regions, and visuals that need crisp scaling and easy interaction.
  • Combine both: use SVG for UI and labels, and Canvas or WebGL for heavy rendering behind it.

? Tips & Best Practices

  • Canvas crispness: scale the backing store using devicePixelRatio for HiDPI / retina displays.
  • SVG responsiveness: always set a viewBox and control size with CSS; avoid fixed width/height for flexible layouts.
  • Animation: use requestAnimationFrame for smooth, synced updates (for both Canvas and SVG).
  • Accessibility: add aria-label or <title> to SVG; Canvas usually needs separate text or ARIA descriptions.
  • Performance: avoid thousands of SVG DOM nodes for highly dynamic data; switch to Canvas or WebGL when rendering becomes heavy.
  • Maintainability: SVG is easier to inspect and tweak with browser dev tools because shapes stay as DOM elements.

? Try It Yourself

  • Add a <circle> to the SVG and change its fill on hover using CSS only.
  • Animate the Canvas rectangle’s position using requestAnimationFrame to move it left and right.
  • Make the SVG fully responsive: remove fixed width/height, keep a viewBox, and set max-width: 100% via CSS.
  • Export the Canvas as an image using toDataURL() (build your own “Download” button like in the demo).
  • Build a simple bar chart twice: once in Canvas (fast redraw) and once in SVG (easy hover tooltips with events).

? Summary

  • Canvas is a bitmap surface controlled by JavaScript – great for performance-heavy, dynamic graphics.
  • SVG is vector-based and lives in the DOM – ideal for crisp, scalable, and interactive shapes.
  • Canvas requires manual hit-testing and HiDPI handling; SVG gets interactivity and scaling “for free.”
  • Use the strengths of each: Canvas/WebGL for raw drawing power, SVG for structure, accessibility, and UI.