Mastering HTML SVG: A Comprehensive Guide
Scalable Vector Graphics (SVG) is a powerful XML-based markup language for creating two-dimensional graphics. Unlike traditional image formats like JPG or PNG, SVGs aren't pixel-based, so they're resolution-independent.
Why SVG?
- Scalable: Scale without pixelation or loss of quality.
- Programmable: Easily manipulated with CSS and JavaScript.
- Accessible: Supports text and descriptive elements for screen readers.
- Lightweight: Usually smaller file sizes compared to bitmap images for simple graphics.
Basic SVG Syntax
Here's a basic example of an SVG element to create a simple circle:
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
Output Example:
SVG Shapes
Rectangles
<svg height="100" width="100">
<rect x="10" y="10" width="80" height="80" stroke="black" stroke-width="2" fill="green"/>
</svg>
Output Example:
Lines
<svg height="100" width="100">
<line x1="10" y1="10" x2="90" y2="90" stroke="blue" stroke-width="2"/>
</svg>
Output Example:
Ellipse
<svg height="100" width="100">
<ellipse cx="50" cy="50" rx="50" ry="25" style="fill:yellow;stroke:purple;stroke-width:2;" />
</svg>
Output Example:
Styling SVGs
You can easily style SVGs with CSS:
circle {
stroke: blue;
fill: lightblue;
stroke-width: 4;
}
SVG and JavaScript
You can also dynamically manipulate SVGs using JavaScript:
const circle = document.querySelector('circle');
circle.addEventListener('click', function() {
circle.setAttribute('fill', 'blue');
});
Conclusion
HTML SVG offers a multitude of options for creating highly customizable and scalable graphics. Their lightweight nature, combined with programmability and accessibility, makes SVGs an excellent choice for modern web development.