Topic 04 / 08

Web Graphics: SVG vs Canvas

1. Simple Definition

Web page par graphics dikhane ke do modern raste hote hain: SVG (Scalable Vector Graphics) jo mathematical shapes (lines, curves) se banta hai aur kitna bhi zoom karne par kbhi blur nahi hota. Canvas (<canvas>) ek blank digital drawing board hota hai jisme JavaScript se pixel-by-pixel real-time games, animations aur charts draw kiye jaate hain.

2. Real-Life Analogy

📐 Geometry Compass vs Paint Canvas

SVG: Geometry compass se circle banana — chahe chote paper par banao ya 100-foot ke billboard par, circle ki line hamesha 100% sharp aur crisp rahegi!
Canvas: Oil paint se banayi painting — agar painting ko microscope se dekhenge toh paint ke dots (pixels) dikhenge. Game me har second nayi painting banani ho toh Canvas best hai.

3. Why Do We Need It?

Icons aur company logos (Google, Apple) SVG me bante hain taaki Retina aur 4K screens par pixelate na hon. Aur games (jaise Flappy Bird) ya financial live stock charts <canvas> se bante hain.

4. Syntax

<!-- 1. Inline SVG Icon -->
<svg width="100" height="100" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="40" stroke="#2563eb" stroke-width="4" fill="#eff6ff" />
</svg>

<!-- 2. Canvas Board -->
<canvas id="myCanvas" width="300" height="150"></canvas>

5. Basic Example (SVG Shapes & Canvas Script)

<!-- Crisp SVG Star Icon -->
<svg width="60" height="60" viewBox="0 0 24 24" fill="#f59e0b">
  <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
</svg>

<!-- Basic Canvas Drawing -->
<canvas id="boxCanvas" width="200" height="80" style="border:1px solid #cbd5e1; border-radius:6px;"></canvas>
<script>
  const c = document.getElementById("boxCanvas");
  const ctx = c.getContext("2d");
  ctx.fillStyle = "#10b981";
  ctx.fillRect(20, 15, 160, 50);
</script>

6. Output / Expected Result

SVG Star
Canvas 2D Box
JS Painted Pixels

7. Code Explanation

  • viewBox="0 0 100 100": SVG ka coordinate system define karta hai jo responsive scaling ke time aspect ratio maintain rakhta hai.
  • fill & stroke: SVG me background color aur border color ki properties.
  • getContext('2d'): Canvas par 2D drawing tools (brush, paint, lines) activate karta hai.

8. Real-World Example

FontAwesome, Lucide Icons, aur Heroicons sabhi SVG format use karte hain. Google Maps aur Figma ka editor canvas rendering engine par chalta hai.

9. Common Mistakes

⚠️ Galti: Canvas dimensions CSS se stretch karna

Agar canvas ki width/height CSS me dete hain aur HTML tag me nahi dete, toh canvas ke andar ki drawing stretch hokar blur ho jati hai. Hamesha HTML me width="300" height="150" likhein!

10. Best Practices

  • Icons, logos aur simple illustrations ke liye hamesha SVG use karein.
  • Heavy games, particle effects aur dynamic chart data ke liye Canvas use karein.

11. Try It Yourself

Playground me ek SVG <circle> aur <rect> bana kar unke fill colors change karein.

12. Challenge

SVG me ek traffic light banayein jisme 3 circles hon (Red, Yellow, Green) ek black rectangle ke andar.

13. Interview Questions

💼 Q: SVG aur Canvas me 3 key differences kya hain?

Answer:
1. SVG XML/DOM-based hota hai (har shape ek DOM element hai jisko click listener de sakte hain). Canvas pixel-based bitmap hota hai (DOM element nahi hota).
2. SVG infinite zoom par crisp rehta hai; Canvas zoom karne par pixelate hota hai.
3. SVG small UI icons ke liye fast hota hai; Canvas thousands of moving objects/games ke liye high performance deta hai.

14. Quick Revision

  • SVG = Mathematical vectors (Crisp forever).
  • Canvas = Digital raster whiteboard for JavaScript drawing.
  • viewBox enables fluid responsive scaling.

15. FAQ

Q1. Kya SVG file ko img tag me daal sakte hain?

Haan! <img src="logo.svg" alt="Company Logo"> ki tarah use kiya ja sakta hai.

Q2. Inline SVG ka kya fayda hai?

Inline SVG ko CSS se direct color kiya ja sakta hai (e.g. svg:hover { fill: red; }) aur alag se HTTP request nahi karni padti.

Q3. WebGL kya hota hai?

WebGL canvas ka 3D context hota hai jisse browser me high-end 3D graphics aur Three.js games chalti hain.

Q4. SVG me d attribute kya karta hai path tag me?

'd' ka matlab "draw commands" (e.g. M = Move to, L = Line to, C = Curve to).

Q5. Kya canvas par click event handle kiya ja sakta hai?

Poore canvas par click event milta hai, lekin individual shapes par nahi (shape detect karne ke liye mouse coordinates calculate karne padte hain).

Topic 04 / 08

Web Graphics: SVG vs Canvas

1. Simple Definition

There are two primary paradigms for rendering web graphics: SVG (Scalable Vector Graphics) is based on mathematical coordinates (lines, curves, polygons) that retain infinite crispness regardless of screen zoom or display resolution. Canvas (<canvas>) is a blank pixel grid (bitmap) driven by JavaScript to render dynamic graphics, game engines, physics simulations, and high-performance charts in real time.

2. Real-Life Analogy

📐 Geometric Blueprint vs Oil Painting Canvas

SVG: Drawing a circle with a geometric compass — whether drawn in a pocket notepad or magnified onto a massive highway billboard, the circle outline remains 100% razor sharp!
Canvas: Painting on canvas with an oil brush — zoom in closely with a magnifying glass and individual paint strokes and pixel dots emerge. When 60 new frames must be repainted every second (in video games), Canvas is the undisputed champion.

3. Why Do We Need It?

Icons and corporate logos (Google, Apple, GitHub) are built using SVG to ensure they remain razor sharp on high-density Retina and 4K screens. Real-time games (such as Flappy Bird) and financial trading candlestick charts leverage <canvas> for optimal 60 FPS graphics performance.

4. Syntax

<!-- 1. Inline SVG Icon -->
<svg width="100" height="100" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="40" stroke="#2563eb" stroke-width="4" fill="#eff6ff" />
</svg>

<!-- 2. Canvas Board -->
<canvas id="myCanvas" width="300" height="150"></canvas>

5. Basic Example (SVG Shapes & Canvas Script)

<!-- Crisp SVG Star Icon -->
<svg width="60" height="60" viewBox="0 0 24 24" fill="#f59e0b">
  <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
</svg>

<!-- Basic Canvas Drawing -->
<canvas id="boxCanvas" width="200" height="80" style="border:1px solid #cbd5e1; border-radius:6px;"></canvas>
<script>
  const c = document.getElementById("boxCanvas");
  const ctx = c.getContext("2d");
  ctx.fillStyle = "#10b981";
  ctx.fillRect(20, 15, 160, 50);
</script>

6. Output / Expected Result

SVG Star
Canvas 2D Box
JS Painted Pixels

7. Code Explanation

  • viewBox="0 0 100 100": Establishes the SVG coordinate space and guarantees consistent aspect ratio scaling.
  • <path d="...">: Defines complex shapes using bezier curves and coordinate commands.
  • canvas.getContext("2d"): Retrieves the 2D rendering engine context to draw geometric shapes and images.
  • ctx.fillRect(x, y, w, h): Paints a filled rectangle at the specified pixel coordinates.

8. Real-World Comparison Table

Feature SVG (Scalable Vector Graphics) Canvas (<canvas>)
Rendering Basis Vectors (Mathematical XML Nodes) Pixels (Raster Bitmap)
DOM Accessibility Individual elements exist in DOM (styleable via CSS) Single DOM element (no internal nodes)
Resolution Independence 100% infinite crispness Resolution dependent (can blur if unscaled)
Ideal Use Cases Logos, UI icons, simple diagrams, infographics Fast 2D/3D games, particle engines, live charts

9. Common Mistakes

⚠️ Common Pitfall: Canvas CSS Size vs Internal Resolution

Styling <canvas style="width: 400px;"> without setting the HTML attributes width="400" height="200" stretches the default 300x150 pixel grid, resulting in blurry, pixelated graphics!

10. Best Practices

  • Inline SVG enables direct styling of paths and fills using CSS variables.
  • Always set width and height attributes directly on the <canvas> tag.
  • Compress SVGs using tools like SVGO to eliminate unnecessary editor metadata.

11. Practice Exercise

🎯 Exercise: Crisp SVG Badge

Write an inline SVG displaying a blue circle with a white checkmark icon inside it using <circle> and <polyline> tags.

12. Mini Challenge

⚡ 15-Minute Challenge: Interactive Canvas Ball

Create an HTML5 canvas and use JavaScript's requestAnimationFrame to animate a simple bouncing ball across the canvas bounds!

13. Interview Questions

💼 Q: When should you select SVG over Canvas, and vice versa?

Answer: Choose SVG when creating UI icons, logos, or elements requiring CSS styling, hover interactions, or DOM event listeners. Choose Canvas when rendering high-frequency animations, games, or manipulating thousands of visual objects where DOM overhead would degrade framerates.

14. Summary / Cheat Card

  • SVG: XML vector graphics, part of the DOM, infinite scaling.
  • Canvas: High-speed pixel raster buffer manipulated through JavaScript.
  • Use SVG for UI elements; use Canvas for real-time games and high-volume data streams.

15. FAQ

Q1. Can CSS hover animations be applied to SVG elements?

Yes! Inline SVG paths can be styled with CSS transitions and hover pseudo-classes just like HTML elements.

Q2. Can Canvas handle 3D graphics?

Yes, by initializing a WebGL or WebGPU rendering context: canvas.getContext("webgl").

Q3. Why does an SVG file have a smaller file size than a PNG?

SVG files store mathematical instructions (e.g. radius and center points) instead of storing millions of individual color pixel values.

Q4. Can you export an HTML5 Canvas drawing to an image?

Yes, using the built-in method canvas.toDataURL("image/png").

Q5. Are SVG files accessible to screen readers?

Yes, by providing <title> and <desc> tags inside the SVG with role="img".