HTML — Lesson 24
HTML SVG Basics
Creating scalable vector graphics inline in HTML.
HTML SVG Basics
SVG (Scalable Vector Graphics) defines vector shapes using XML. Unlike Canvas, SVG elements are part of the DOM and can be styled and interacted with.
Inline SVG
<svg width="200" height="200" viewBox="0 0 200 200">
<!-- Circle -->
<circle cx="100" cy="100" r="80"
fill="#4ecdc4" stroke="#333" stroke-width="2"/>
<!-- Text -->
<text x="100" y="105" text-anchor="middle"
fill="white" font-size="20">SVG</text>
</svg>
SVG Shapes
<svg width="400" height="200">
<!-- Rectangle -->
<rect x="10" y="10" width="80" height="60"
fill="#ff6b6b" rx="8"/>
<!-- Circle -->
<circle cx="150" cy="40" r="30" fill="#4ecdc4"/>
<!-- Ellipse -->
<ellipse cx="260" cy="40" rx="50" ry="25" fill="#764ba2"/>
<!-- Line -->
<line x1="10" y1="100" x2="350" y2="100"
stroke="#333" stroke-width="2"/>
<!-- Polygon -->
<polygon points="200,130 230,200 170,200" fill="#ffc107"/>
</svg>
Styling SVG with CSS
<style>
svg circle {
transition: fill 0.3s ease;
cursor: pointer;
}
svg circle:hover {
fill: #ff6b6b;
}
</style>
SVG vs Canvas
| Feature | SVG | Canvas |
|---|---|---|
| Resolution | Scalable (vector) | Pixel-based (raster) |
| DOM | Yes (each shape is an element) | No (single element) |
| Events | Per-shape events | Manual hit detection |
| Best for | Icons, logos, charts, UI | Games, photo editing, complex animations |
Tip: Use SVG for icons, logos, illustrations, and UI elements. Use Canvas for games, complex particle systems, and pixel-level image manipulation.
Practice what you learned in the Deoit Editor — a free, browser-based code editor.
Open Editor →