Scalable Vector Graphics (SVG) is an XML-based image format that is used to display 2D vector graphics on webpages. The major benefit of using this image format while displaying images on the web is that images created using it can be scaled up or down without distorting their quality because they are composed using vector shapes instead of pixels. Additional benefits of SVG images include:-

  • An ability to be searched and indexed by search engines.
  • They can contain hyperlinks to other documents
  • Users can print them in high quality at any resolution.
  • SVG images can be animated using a browser’s built in animation elements

The SVG element in HTML 5 allows you to embed images directly on your webpage documents. Additionally, you can draw various shapes using scripted code as we saw with the <canvas> element. Below are a few examples that illustrate how code for drawing various shapes using the <svg> element works.

Drawing a line

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

Drawing an arch

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ""> 
<svg viewBox = "0 0 1100 400" version = "1.1">
    <g stroke = "navy" stroke-width = "3" fill = "none">
        <path d = "M 300 50 a 150 50 0 0 0 250 50"/>
        <path d = "M 300 200 a 150 50 0 0 1 250 50"/>
        <path d = "M 700 50 a 150 50 0 1 0 250 50"/>
        <path d = "M 700 200 a 150 50 0 1 1 250 50"/>
    <g text-anchor = "middle" font-size = "25" font = "sans-serif">
        <text x = "400" y = "20">
        <text x = "825" y = "20">
    <g text-anchor = "end" font-size = "25" font = "sans-serif" rotate = "0">
        <text x = "230" y = "70">
        <text x = "230" y = "220">

Drawing a rectangle

<svg width="400" height="110">
  <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />

Drawing a circle

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

Drawing text

<svg height="30" width="200">
  <text x="0" y="15" fill="red">I love SVG!</text>

Differences between SVG and Canvas Elements

Both <canvas> and <svg> elements are new features that were introduced with HTML 5. They can both be used to create rich graphics for the web, but they have distinct differences. Below is a two-sided table that compares them.

SVG has better scalability. So it can be printed with high quality at any resolutionCanvas has poor scalability. Hence it is not suitable for printing on higher resolution
SVG gives better performance with smaller number of objects or larger surface.Canvas gives better performance with smaller surface or larger number of objects.
SVG can be modified through script and CSSCanvas can be modified through script only
SVG is vector based and composed of shapes.Canvas is raster based and composed of pixel.