HTML5 SVG
SVG is defined as Scalable Vector Graphics.
HTML5 supports inline SVG.
The HTML <svg>
element is a container for SVG graphics.
SVG has various methods for drawing paths, boxes, circles, text, and graphic images.
What is SVG?
- SVG stands for Scalable Vector Graphics
- SVG is used to define vector-based graphics for the web
- SVG is defined in XML format
- SVG images do not lose any quality when zoomed or resized
- SVG is a standard of the World Wide Web Consortium
Advantages of SVG
Compared to other image formats (like JPEG and GIF), the advantages of using SVG include:
- SVG images can be created and edited with any text editor
- SVG images can be searched, indexed, scripted, or compressed
- SVG is scalable
- SVG images can be printed with high quality at any resolution
- SVG images can be scaled without degrading the image quality
Browser Support
The numbers in the table specify the first browser version that fully supports the element.
Element | |||||
---|---|---|---|---|---|
<svg> |
4.0 | 9.0 | 3.0 | 3.2 | 10.1 |
Embedding SVG Directly into HTML Pages
In HTML5, you can embed SVG elements directly into the HTML page.
SVG Circle
Example
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" />
</svg>
Result:
SVG Star
Example
<!DOCTYPE html>
<html>
<body>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="190">
<polygon points="100,10 40,180 190,60 10,60 160,180"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;">
</svg>
</body>
</html>
Result:
To learn more about SVG, visit the SVG Tutorial.
Differences Between SVG and Canvas
SVG is a language for describing 2D graphics in XML.
Canvas draws 2D graphics using JavaScript.
SVG is based on XML, which means every element is available in the SVG DOM. You can attach JavaScript event handlers to elements.
In SVG, every drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape.
Canvas is rendered pixel by pixel. Once the graphic is drawn, it is forgotten by the browser. If its position is changed, the entire scene needs to be redrawn, including any objects that might have been covered by the graphic.
Comparison Between Canvas and SVG
The table below outlines some differences between Canvas and SVG.
Canvas | SVG |
---|---|
Resolution dependent<br> No support for event handlers<br> Inferior text rendering capabilities<br> Images can be saved as .png or .jpg<br> Best suited for graphic-intensive games | Resolution independent<br> Supports event handlers<br> Best for applications with large rendering areas (like Google Maps)<br> Complexity can slow down rendering (any application that overuses the DOM will be slow)<br> Not suitable for game applications |