Home › HTML Masterclass › Multimedia and Graphics
Module 8: GraphicsAdvanced

32. Canvas vs SVG (<canvas> vs <svg>)

The difference between vector graphics (SVG) and a pixel drawing board (Canvas)

Real-life analogy

SVG is like a picture drawn on a rubber balloon that never breaks up (Pixelate) no matter how much you enlarge it. Canvas is a blank drawing sheet on which pictures are drawn with the brush of JavaScript.

Explanation

SVG (Scalable Vector Graphics): XML-based lines, circles and shapes. They run on mathematical calculation, so they never break up even on 4K or 8K displays. Best for logos and icons.

Canvas (<canvas>): A pixel-based blank board. Lines and animations are drawn on it through JavaScript (getContext('2d')). Best for web games and charts.

Golden rules

  • Always use SVG for logos and icons.
  • JavaScript is required to draw anything on a canvas.

Common mistake

Using a heavy PNG photo for a logo. A light and scalable SVG should be used instead.

Example code

<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; padding: 20px;">
  <h4>1. Pure SVG (star):</h4>
  <svg width="50" height="50" viewBox="0 0 24 24" fill="#f59e0b">
    <polygon points="12,2 15,9 22,9 17,14 19,21 12,17 5,21 7,14 2,9 9,9"/>
  </svg>

  <h4 style="margin-top: 10px;">2. HTML Canvas (JS render):</h4>
  <canvas id="myCanvas" width="160" height="50" style="border:1px solid #cbd5e1; border-radius: 4px;"></canvas>
  <script>
    const c = document.getElementById("myCanvas");
    const ctx = c.getContext("2d");
    ctx.fillStyle = "#10b981";
    ctx.fillRect(10, 10, 140, 30);
    ctx.fillStyle = "white";
    ctx.font = "bold 12px sans-serif";
    ctx.fillText("Canvas Drawn!", 30, 30);
  </script>
</body>
</html>

Run & edit this in the live editor

Quick quiz

Which graphic format never gets pixelated no matter how much you zoom in?

  1. JPEG
  2. PNG
  3. SVG
  4. GIF
Show answer

Answer: SVG

SVG (Scalable Vector Graphics) works on mathematical lines, so it never breaks up.

← All 38 lessons