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 multiple ways to draw 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 uses XML format to define graphics
  • SVG images can be enlarged or resized without loss of graphic quality
  • SVG is a standard of the World Wide Web Consortium

SVG Advantage

The advantages of using SVG over other image formats such as JPEG and GIF are:

  • SVG images can be created and modified with a 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 can be scaled up without loss of image quality

Browser support

The number in the table represents the first browser version number that supports the element.

ElementChromeEdgeFirefoxSafariOpera
<svg>4.09.03.03.210.1

Embed SVG directly into HTML pages

In HTML5, you can embed SVG elements directly into HTML pages.

SVG circle

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

Program Output:

SVG pentagram

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 tutorials, visit SVG Tutorials.


Difference between SVG and Canvas

SVG is a language for describing 2D graphics using XML.

Canvas uses JavaScript to draw 2D graphics.

SVG is based on XML, which means that every element in the SVG DOM is available. You can attach JavaScript event handlers to an element.

In SVG, each drawn graphic is considered an object. If the properties of the SVG object change, the browser can automatically reproduce the graphic.

Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it doesn’t continue to get the browser’s attention. If its position changes, the entire scene also needs to be redrawn, including any objects that may have been covered by graphics.


Canvas vs SVG

The following table lists some of the differences between canvas and SVG.

CanvasSVG
Resolution dependent.
Event handlers are not supported
Weak text rendering capabilities.
Ability to save the resulting image in .png or .jpg format

Best for graphics-intensive games where many objects are redrawn frequently
Resolution independent.
Support event handler.
Best for applications with large rendering areas (like Google Maps)
High complexity slows down rendering (any application that overuses the DOM is not fast)
Not suitable for gaming applications