HTML · Chapter 41 of 45

HTML Canvas and SVG

HTML5 offers two ways to draw graphics: <canvas> for pixel-based, JavaScript-driven drawing, and <svg> for vector-based graphics defined directly in markup.

Canvas is ideal for dynamic, pixel-manipulation-heavy tasks like games or charts that redraw often. SVG is ideal for scalable icons, logos, and illustrations that stay crisp at any zoom level and can be styled with CSS.

Syntax
<canvas id="c"></canvas> / <svg><circle .../></svg>

Canvas basics

<canvas> is an empty drawing surface; you use JavaScript's Canvas API (getContext('2d')) to draw shapes, images, and animations pixel by pixel.

SVG basics

SVG uses XML-like tags such as <circle>, <rect>, and <path> directly in HTML, producing resolution-independent vector graphics that scale perfectly.

Example 1 (html)
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
  const ctx = document.getElementById("myCanvas").getContext("2d");
  ctx.fillStyle = "blue";
  ctx.fillRect(10, 10, 100, 50);
</script>
Output
(draws a blue 100x50 rectangle on the canvas)

JavaScript is required to draw anything on a canvas element.

Example 2 (html)
<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" fill="green" />
</svg>
Output
(draws a green circle, scales cleanly at any size)

SVG shapes are defined declaratively in markup, no JavaScript needed.

Key points

  • <canvas> is pixel-based and requires JavaScript to draw.
  • <svg> is vector-based and defined declaratively in markup.
  • SVG scales perfectly at any zoom level; canvas can pixelate.
  • SVG elements can be styled and animated with CSS.
💡 Note: For icons and logos, prefer SVG; for games and complex pixel manipulation, prefer canvas.

📝 Quick Quiz

1. Which is vector-based and scales without pixelation?

2. What is required to draw on a canvas element?

3. Which is better suited for a company logo?