HTML SVG
31 March 2025 | Category: HTML
Introduction to SVG
SVG (Scalable Vector Graphics) is an XML-based markup language for creating vector-based graphics that can be scaled without losing quality. Unlike raster images (JPG, PNG), SVGs remain crisp at any resolution.
Why Use SVG?
- Scalability: No loss of quality when resized.
- Small File Size: Uses XML code, often smaller than raster images.
- CSS & JavaScript Support: Styles and animations can be applied.
- Interactive: Can be manipulated with JavaScript.
Basic SVG Structure
SVG elements are defined within <svg>
tags:
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="50" fill="blue" />
</svg>
Common SVG Elements
1. Rectangle (<rect>
)
<svg width="200" height="200">
<rect x="20" y="20" width="100" height="50" fill="red" stroke="black" stroke-width="2" />
</svg>
x
,y
: Position of the rectangle.width
,height
: Dimensions.fill
: Fill color.stroke
: Border color.stroke-width
: Border thickness.
2. Circle (<circle>
)
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" fill="blue" />
</svg>
cx
,cy
: Center coordinates.r
: Radius.
3. Line (<line>
)
<svg width="200" height="200">
<line x1="10" y1="10" x2="190" y2="190" stroke="black" stroke-width="3" />
</svg>
x1
,y1
: Start point.x2
,y2
: End point.
4. Polygon (<polygon>
)
<svg width="200" height="200">
<polygon points="50,10 90,90 10,90" fill="green" />
</svg>
points
: A list of coordinates for vertices.
5. Text (<text>
)
<svg width="200" height="100">
<text x="10" y="50" font-size="20" fill="black">Hello, SVG!</text>
</svg>
x
,y
: Position.font-size
: Font size.
Applying CSS to SVG
SVG elements can be styled using CSS:
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" class="circle-style" />
</svg>
<style>
.circle-style {
fill: orange;
stroke: black;
stroke-width: 3px;
}
</style>
SVG Animation
Using <animate>
:
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" fill="blue">
<animate attributeName="r" from="10" to="50" dur="1s" repeatCount="indefinite" />
</circle>
</svg>
attributeName
: Property to animate.from
&to
: Start and end values.dur
: Duration.repeatCount
: How many times to repeat.
Interactivity with JavaScript
<svg width="200" height="200" id="svgCanvas">
<circle id="myCircle" cx="100" cy="100" r="50" fill="red" />
</svg>
<script>
document.getElementById("myCircle").addEventListener("click", function() {
this.setAttribute("fill", "blue");
});
</script>
Conclusion
SVG is a powerful way to create scalable graphics, animations, and interactive designs. It’s widely used in web development for icons, logos, and illustrations.