HTML <svg> Tag โ Scalable Vector Graphics
๐ Introduction
The <svg> tag is used to create vector-based graphics directly in HTML.
Unlike images (<img>), SVG graphics:
- Do not lose quality when resized
- Are lightweight
- Can be styled and animated with CSS/JavaScript
SVG stands for Scalable Vector Graphics.
๐งฑ Basic Syntax
<svg width="200" height="200">
<!-- shapes go here -->
</svg>
๐ก Example 1: Circle
<!DOCTYPE html>
<html>
<head>
<title>SVG Example</title>
</head>
<body>
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" fill="blue" />
</svg>
</body>
</html>
๐ฅ๏ธ Output Explanation
- A blue circle appears
cx= center X positioncy= center Y positionr= radius
๐ฏ Common SVG Shapes
1. Circle
<circle cx="50" cy="50" r="40" fill="red" />
2. Rectangle
<rect width="100" height="60" fill="green" />
3. Line
<line x1="0" y1="0" x2="200" y2="200" stroke="black" />
4. Text
<text x="10" y="50" fill="black">Hello SVG</text>
๐จ Example 2: Multiple Shapes
<svg width="300" height="200">
<rect x="10" y="10" width="100" height="80" fill="orange" />
<circle cx="200" cy="60" r="40" fill="blue" />
</svg>
๐ฏ Why <svg> is Important
- Perfect for logos and icons
- Looks sharp on all screen sizes
- Can be animated
- Used in modern UI design
โ๏ธ SVG vs <canvas>
| Feature | <svg> |
<canvas> |
|---|---|---|
| Type | Vector | Pixel-based |
| Scalability | Infinite | Fixed resolution |
| Editing | Easy (DOM-based) | Hard (JS-only) |
| Use case | Icons, UI, logos | Games, animations |
โ ๏ธ Important Notes
- SVG is written in XML-like syntax
- Each shape is an element
- Can be styled with CSS
๐ซ Common Mistakes
- Confusing SVG with images โ
- Forgetting coordinates โ
- Not setting width/height โ
๐งช Mini Exercise
Create a page that includes:
- A red circle
- A green rectangle
- A text label inside SVG
- Try changing colors and positions