SVG (Scalable Vector Graphics) is an XML-based format for creating vector graphics. SVG images are scalable and can be used to create intricate graphics, animations, and interactive elements without losing quality.
Here is a basic example of an SVG element:
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
SVG allows you to create various shapes such as rectangles, circles, and lines. Below are examples of different shapes you can create with SVG.
Rectangle
<svg width="300" height="200">
<rect width="100" height="100" style="fill:blue;stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
<svg height="210" width="400">
<line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" />
</svg>
The path element allows you to define complex shapes. The d attribute contains a series of commands and parameters for drawing the shape.
<svg width="300" height="200">
<path d="M150 0 L75 200 L225 200 Z" />
</svg>
SVG elements can be styled using CSS. You can apply styles directly within the SVG element or through external stylesheets.
<svg width="100" height="100" style="border:1px solid black">
<circle cx="50" cy="50" r="40" class="my-circle" />
</svg>
<style>
.my-circle {
fill: yellow;
stroke: black;
stroke-width: 2;
}
</style>
SVG supports animation through the animate element. You can animate attributes such as position, size, color, and more.
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red">
<animate attributeName="cx" from="50" to="150" dur="1s" repeatCount="indefinite" />
</circle>
</svg>
SVG elements can be manipulated using JavaScript, allowing for dynamic and interactive graphics.
<svg id="svgElement" width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
<script>
document.getElementById("svgElement").addEventListener("click", function() {
alert("SVG element clicked!");
});
</script>
Here are some important notes and best practices for using SVG: