HTML SVG

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.

Basic SVG Example

Here is a basic example of an SVG element:

Try yourself
        
            <svg width="100" height="100">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
        
    

SVG Shapes

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
Try yourself
        
            <svg width="300" height="200">
    <rect width="100" height="100" style="fill:blue;stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
        
    

Circle
Try yourself
        
            <svg width="100" height="100">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
        
    

Line
Try yourself
        
            <svg height="210" width="400">
    <line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" />
</svg>
        
    

SVG Paths

The path element allows you to define complex shapes. The d attribute contains a series of commands and parameters for drawing the shape.

Try yourself
        
            <svg width="300" height="200">
    <path d="M150 0 L75 200 L225 200 Z" />
</svg>
        
    

Styling SVG

SVG elements can be styled using CSS. You can apply styles directly within the SVG element or through external stylesheets.

Try yourself
        
            <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>
        
    

Animating SVG

SVG supports animation through the animate element. You can animate attributes such as position, size, color, and more.

Try yourself
        
            <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 and JavaScript

SVG elements can be manipulated using JavaScript, allowing for dynamic and interactive graphics.

Try yourself
        
            <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>
        
    

Important Notes

Here are some important notes and best practices for using SVG: