HTML5 SVG Scalable Vector Graphics



Scalable Vector Graphics

Scalable Vector Graphics (SVG) is an XML-based language for creating two-dimensional graphics. It’s implemented by using tags defined by the SVG XML namespace and embedded in HTML5 documents within opening and closing <svg> elements.

You can access SVG objects via the DOM. elements support attributes, styles, and event handlers.

The following code is an example of an SVG graphic with event handlers:

<head>
<script language="javascript">
    function Red(evt) {
        var circle = evt.target;
        circle.setAttribute("style", "fill: red");
    }
    function Green(evt) {
        var circle = evt.target;
        circle.setAttribute("style", "fill: green");
    }
    </script>
</head>
<body>
    <svg style="padding:45px;">
       <circle id="Circle" cx="50" cy="50" r="50" fill="green" onmouseover="Red(evt)"
            onmouseout="Green(evt)" />
    </svg>   
</body>

All the shape-drawing and line-drawing functionality you saw in the <canvas> element discussion exists for SVG as well with different syntax.

You can take use of the <rect> element to create background rectangle and a series of <circle> elements to create lights-circles.

The <rect> element needs an (x,y) coordinate to be drawn, along with a width and height to establish the size and the fill attribute sets the color to be used to fill the shape.

The following code produces an complete example using the properties described above:

<svg>
<rect id="lightStandard" x="100" y="100" width="60" height="200" fill="black" />
    <circle id="redLight" cx="129" cy="145" r="25" fill="red" />
    <circle id="amberLight" cx="129" cy="205" r="25" fill="yellow" />
    <circle id="greenLight" cx="129" cy="265" r="25" fill="green" />
</svg>

Drawing SVG shapes using functions

SVG also supports the same basic shape-drawing functions as the canvas context. The following code segment shows the use of the polyline, polygon, line, and ellipse:

<svg style="padding:15px;">
    <polygon points="10,15 30,35 10,85 100,85, 70,35,100,15" fill="purple" />
    <polyline points="10,150 30,170 50,132 62,196 78,165 96,170"
              style="stroke:orange; fill:none; stroke-width:5;" />
    <line x1="150" y1="100" x2="150" y2="150" style="stroke:blue;stroke-width:3" />
    <ellipse cx="250" cy="150" rx="30" ry="55" fill="green" />
    <text x="10" y="10" style="stroke: black;stroke-width:1;">
        Examples of SVG Shapes and Text
    </text>
</svg>

Drawing SVG images

SVG also supports rendering existing graphics in the form of external image files, as shown in the code below:

<svg id="mySVG">
    <image href="image.jpg" width="250" height="100" />
</svg>

Ads Right