Scalable Vector Graphics in HTML5

Basic concepts and usage

Scalable Vector Graphics (SVG) are part of the vector family of graphics. They have several benefits over their raster counterparts: JPEG, GIF, and PNG. In this article, explore the basic concepts and usage of SVG graphics in HTML5. Learn about drawing, filters, gradients, text, and adding SVG XML to web pages.

Share:

Jeremy J. Wischusen, Web Application Architect, Binary Neuron L.L.C.

Jeremy Wischusen photoJeremy Wischusen has over 13 years of experience designing websites and applications for clients such as Purple Communications, myYearbook.com, HBO, and others, building both front- and back-end systems with Flash, Flex, jQuery, PHP, MySQL, MSSQL, and PostgreSQL. He has taught web design, Flash, and ActionScript for clients such as Wyeth Pharmaceuticals, The Vanguard Group, Bucks County Community College, and The University of the Arts.



31 January 2012

Also available in Chinese Russian Japanese Spanish

Introduction

Scalable Vector Graphics (SVG) are part of the vector-based family of graphics. They are different from raster-based graphics, which store the color definition for each pixel in an array of data. The most common raster-based formats used on the web today are JPEG, GIF, and PNG, and each of these formats has strengths and weaknesses.

Frequently used abbreviations

  • CSS: Cascading Style Sheets
  • GIF: Graphics Interchange Format
  • GUI: Graphical User Interface
  • HTML: Hypertext Markup Language
  • JPEG: Joint Photographic Experts Group
  • PNG: Portable Network Graphics
  • SVG: Scalable Vector Graphics
  • XML: Extensible Markup Language

SVG has several advantages over any raster-based format:

  • SVG graphics are created using mathematical formulas that require far less data to be stored in the source file because you don't have to store the data for each individual pixel.
  • Vector images scale better. With images on the web, trying to scale an image up from its original size can result in distorted (or pixilated) images.

    The original pixel data was designed for a specific size. When the image is no longer that size, the program displaying the image guesses as to what data to use to fill in the new pixels. Vector images are more resilient; when the size of the image changes, the mathematical formulas can be adjusted accordingly.

  • The source file size tends to be smaller, so SVG graphics load faster than their raster counterparts and use less bandwidth.
  • SVG images are rendered by the browser and can be drawn programmatically. They can be changed dynamically, making them especially suited for data-driven applications, such as charts.
  • The source file for an SVG image is a text-based file, so it's both accessible and search engine friendly.

In this article, learn about the benefits of SVG formats and how they can help in your web design efforts in HTML5.


SVG basics

To create an SVG graphic you use an entirely different process than when creating a JPEG, GIF, or PNG file. JPEG, GIF, and PNG files are usually created with an image editing program, such as Adobe Photoshop. SVG images are typically created using an XML-based language. There are SVG editing GUIs that will generate the underlying XML for you. However, for this article, it is assumed you're working with the raw XML. See Resources for information about SVG editing programs.

Listing 1 shows an example of a simple SVG XML file that draws a red circle with a 2-pixel black border.

Listing 1. SVG XML file
<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>

The code above results in the drawing in Figure 1.

Figure 1. Red circle with 2-pixel black border
A red circle with a 2-pixel border

Creating basic shapes

With SVG graphics, you use XML tags to create shapes, and Table 1 shows these XML elements.

Table 1. XML elements for creating SVG graphics
ElementDescription
lineCreates a simple line.
polylineDefines shapes built from multiple line definitions.
rectCreates a rectangle.
circleCreates a circle.
ellipseCreates an ellipse.
polygonCreates a polygon.
pathAllows for the definition of arbitrary paths.

The line element

The line element is the basic drawing element. Listing 2 shows how to create a horizontal line.

Listing 2. Creating a horizontal line
<svg xmlns="http://www.w3.org/2000/svg" version='1.1'
 width="100%" height="100%" >
   <line x1='25' y1="150" x2='300' y2='150'
           style='stroke:red;stroke-width:10'/>
 </svg>

The code from Listing 2 results in the drawing in Figure 2.

Figure 2. Basic horizontal line
A flat red horizontal line

The root SVG tag has width and height attributes that define the area of the canvas available for drawing. They work like the height and width attributes of other HTML elements. In this case, the canvas is set to take up all of the available space.

The example also uses the style tag. SVG graphics support styling of their content with a variety of methods. The styles in this article are included to make them stand out or when certain attributes, such as stroke colors and widths, are required to make the drawing render. Resources has more information about styling SVG graphics.

You can create a line definition by defining the starting and ending x and y coordinates relative to the canvas. The x1 and y1 attributes are the start coordinates and the x2 and y2 attributes are the end coordinates. To change the direction of the line, you simply change the coordinates. For example, by modifying the previous example you can produce a diagonal line, as shown in Listing 3.

Listing 3. Creating a diagonal line
                <svg xmlns="http://www.w3.org/2000/svg" version='1.1'
                width="100%" height="100%" >
                    <line x1="0" y1="0" x2="200" y2="200"
                        style='stroke:red;stroke-width:10'/>
                </svg>

Figure 3 shows the result of the code in Listing 3.

Figure 3. Diagonal line
A red diagonal Line

The polyline element

A polyline is a drawing made up of multiple line definitions. The example in Listing 4 creates a drawing that looks like a set of stairs.

Listing 4. Creating polyline stairs
<svg xmlns="http://www.w3.org/2000/svg"
width="100%" height="100%" version='1.1'>
   <polyline points="0,40 40,40 40,80 80,80 80,120 120,120 120,160"
         style="fill:white;stroke:red;stroke-width:4"/>
</svg>

The code from Listing 4 results in the drawing in Figure 4.

Figure 4. Polyline stairs
A red line that looks like climbing stairs

You create a polyline by using the points attribute and defining pairs of x and y coordinates separated by commas. In the example, the first point is defined as 0,40 where 0 is the x value and 40 is the y value. However, a single set of points is not enough to get anything to display on the screen because that only tells the SVG renderer where to start. At a minimum, you need two sets of points: a starting point and an ending point (for example, points="0,40 40,40”).

As with the simple line drawings, the lines need not be strictly horizontal or vertical. If you change the values of the previous example, as in Listing 5, you can produce irregular line shapes.

Listing 5. Creating an irregular line
<svg xmlns="http://www.w3.org/2000/svg"
width="100%" height="100%" version='1.1'>
   <polyline points="20,20 40,25 60,40 80,120 120,140 200,180"
         style="fill:white;stroke:red;stroke-width:3"/>
</svg>

The code from Listing 5 yields the drawing shown in Figure 5.

Figure 5. Irregular line
A red line that runs from left to right, up to down, with several different turns

The rect element

Creating a rectangle is as simple as defining a width and a height, as shown in Listing 6.

Listing 6. Creating a rectangle
<svg xmlns="http://www.w3.org/2000/svg"
width="100%" height="100%" version='1.1'>
    <rect width="300" height="100"
          style="fill:red"/>
</svg>

The code from Listing 6 results in the drawing in Figure 6.

Figure 6. Rectangle
A red rectangle

You can also create a square with the rect tag; a square is simply a rectangle where the height and width are the same.

The circle element

You create a circle by defining the x and y coordinates of the center of the circle and a radius, as shown in Listing 7.

Listing 7. Creating a circle
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <circle cx="100" cy="50" r="40" fill="red"/>
</svg>

The code from Listing 7 results in the drawing in Figure 7.

Figure 7. Circle
A circle filled with black

The cx and cy attributes define the center of the circle relative to the drawing canvas. Because the radius is half the width of the circle, when defining the radius remember that the overall width of the image will be twice that value.

The ellipse element

An ellipse is basically a circle with code that defines two radii, as shown in Listing 8.

Listing 8. Creating an ellipse
                <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
                    <ellipse cx="300" cy="80" rx="100" ry="50" style="fill:red;"/>
                </svg>

The code from Listing 8 results in the drawing in Figure 8.

Figure 8. Ellipse
An ellipse filled with red.

Again, the cx and cy attributes define the center coordinates relative to the canvas. With an ellipse, though, you define one radius for the x axis and one for the y axis using the rx and ry attributes.

The polygon element

A polygon is a shape that contains at least three sides. Listing 9 creates a simple triangle.

Listing 9. Creating a triangle
                <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
                    <polygon points="200,10 250,190 160,210"
                        style="fill:red;stroke:black;stroke-width:1"/>
                </svg>

The code from Listing 9 results in the drawing in Figure 9.

Figure 9. Triangle polygon
A polygon triangle filled with red

Similar to the polyline element, you create polygons by defining pairs of x and y coordinates using the points attribute.

You can create polygons with any number of sides by adding x and y pairs. By modifying the previous example, you can create a four-sided polygon, as shown in Listing 10.

Listing 10. Creating a four-sided polygon
                <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
                    <polygon points="220,10 300,210 170,250 123,234"
                        style="fill:red;stroke:black;stroke-width:1"/>
                </svg>

The code from Listing 10 results in the drawing in Figure 10.

Figure 10. Four-sided polygon
A 4-sided polygon filled with red

You can even create complex shapes using the polygon tag. Listing 11 creates a drawing of a star.

Listing 11. Creating a star
 <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
      <polygon points="100,10 40,180 190,60 10,60 160,180 100,10"
            style="fill:red;stroke:black;stroke-width:1"/>
</svg>

The code from Listing 11 results in the drawing in Figure 11.

Figure 11. Star polygon
A polygon star filled with red

The path element

With the path element, the most complex of all the drawing elements, you can create arbitrary drawings using a set of specialized commands. The path element supports the commands in Table 2.

Table 2. Commands supported by the path element
CommandDescription
MMove to
LLine to
HHorizontal line to
VVertical line to
CCurve to
SSmooth curve to
QQuadratic Bezier curve to
TSmooth quadratic Bezier curve to
AElliptical arc to
ZClose path to

You can use these commands in upper or lowercase form. When the command is in uppercase, absolute positioning is applied. When it is in lowercase, relative positioning is applied. Supplying examples of all the commands is outside the scope of this article. However, the following examples demonstrate their basic usage.

You can create any of the simple shapes from previous examples in this article using the path element. Listing 12 creates a basic triangle using the path element.

Listing 12. Creating a triangle using the path element
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <path d="M150 0 L75 200 L225 200 Z" style="fill:red"/>
</svg>

The code from Listing 12 results in the drawing in Figure 12.

Figure 12. Triangle using the path element
A triangle filled with red.

The list of commands is defined using the d attribute. In this example, the drawing starts at an x coordinate of 150 and a y coordinate of 0, as defined by the move to command (M150 0). It then draws a line to the x/y coordinates x = 75 and y = 200 using the line to command (L75 200). Next, it draws another line using another line to command (L225 200). Finally, the drawing is closed off using the close to command (Z). No coordinates are supplied with the Z command because to close the path you are, by definition, drawing a line from the current position back to the starting point of the drawing (in this case, x = 150 y =0).

The intention here was to show a basic example; if all you want is a simple triangle, you're better off using the polygon tag.

The real power of the path element is the ability to create custom shapes, as shown in Listing 13. The example is from the World Wide Web Consortium (W3C) document, Scalable Vector Graphics (SVG) 1.1 (Second Edition) (see Resources).

Listing 13. Creating a custom shape using the path element
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
       <path d="M300,200 h-150 a150,150 0 1,0 150,-150 z"
                fill="red" stroke="blue" stroke-width="5"/>
       <path d="M275,175 v-150 a150,150 0 0,0 -150,150 z"
                 fill="yellow" stroke="blue" stroke-width="5"/>
       <path d="M600,350 l 50,-25
                 a25,25 -30 0,1 50,-25 l 50,-25
                 a25,50 -30 0,1 50,-25 l 50,-25
                 a25,75 -30 0,1 50,-25 l 50,-25
                 a25,100 -30 0,1 50,-25 l 50,-25"
                 fill="none" stroke="red" stroke-width="5"/>
</svg>

The code from Listing 13 results in the drawing in Figure 13.

Figure 13. Custom shape using the path element
A cirlce pie chart with 1/4 borken out as well as a line with bumps in it.

With the path element you can create complex drawings, such as charts and wave lines. Note that this example uses multiple path elements. You are not limited to a single drawing element within the root SVG tag when creating drawings.


Filters and gradients

In addition to the basic CSS styling in many of the examples thus far, SVG graphics also support the use of filters and gradients. In this section, learn how to apply filters and gradients to SVG drawings.

Filters

You can use filters to apply special effects to SVG graphics. SVG supports the following filters.

  • feBlend
  • feColorMatrix
  • feComponentTransfer
  • feComposite
  • feConvolveMatrix
  • feDiffuseLighting
  • feDisplacementMap
  • feFlood
  • feGaussianBlur
  • feImage
  • feMerge
  • feMorphology
  • feOffset
  • feSpecularLighting
  • feTile
  • feTurbulence
  • feDistantLight
  • fePointLight
  • feSpotLight

See Resources for a detailed explanation about using these filters.

Listing 14 creates a drop shadow effect that is applied to a rectangle.

Listing 14. Creating a drop shadow effect for a rectangle
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
          <defs>
                   <filter id="f1" x="0" y="0"
                             width="200%" height="200%">
                         <feOffset result="offOut" in="SourceAlpha"
                              dx="20" dy="20"/>
                         <feGaussianBlur result="blurOut"
                               in="offOut" stdDeviation="10"/>
                         <feBlend in="SourceGraphic"
                                in2="blurOut" mode="normal"/>
                    </filter>
         </defs>
          <rect width="90" height="90" stroke="green"
                   stroke-width="3" fill="yellow" filter="url(#f1)"/>
</svg>

The code from Listing 14 results in the drawing in Figure 14.

Figure 14. Drop shadow effect for a rectangle
A yellow square with a black drop shadow behind it.

You define filters within the def (for definitions) element. The filter in this example is assigned an id of "f1". The filter tag itself has attributes for defining the x and y coordinates and the width and height of the filter. Inside of the filter tag, you use the desired filter elements and set their properties to the desired values.

After defining the filter, you associate it with a particular drawing by using the filter attribute, as shown in the rect element. Set the url value to the value of the id attribute that you assigned the filter.

Gradients

A gradient is a gradual transition from one color to another. Gradients come in two basic forms: linear and radial. The type of gradient applied is determined by the element you use. The following examples show linear and radial gradients applied to an ellipse.

Listing 15 creates an ellipse with linear gradient.

Listing 15. Creating an ellipse with linear gradient
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
         <defs>
            <linearGradient id="grad1" x1="0%" y1="0%"
                     x2="100%" y2="0%">
           <stop offset="0%"
                     style="stop-color:rgb(255,255,0);stop-opacity:1"/>
           <stop offset="100%"
                     style="stop-color:rgb(255,0,0);stop-opacity:1"/>
           </linearGradient>
         </defs>
         <ellipse cx="200" cy="70" rx="85" ry="55"
                        fill="url(#grad1)"/>
</svg>

The code from Listing 15 results in the drawing in Figure 15.

Figure 15. Ellipse with linear gradient
An ellipse with gradiating color from yellow to orange, left to right.

Listing 16 creates an ellipse with radial gradient.

Listing 16. Creating an ellipse with radial gradient
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
             <defs>
                     <radialGradient id="grad1" cx="50%" cy="50%"
                            r="50%" fx="50%" fy="50%">
                     <stop offset="0%"
                            style="stop-color:rgb(255,255,255);stop-opacity:0"/>
                     <stop offset="100%"
                            style="stop-color:rgb(255,0,0);stop-opacity:1"/>
                     </radialGradient>
             </defs>
             <ellipse cx="200" cy="70" rx="85" ry="55"
                     fill="url(#grad1)"/>
</svg>

The code from Listing 16 results in the drawing in Figure 16.

Figure 16. Ellipse with radial gradient
An ellipse with gradiant color from red to white, outer edges to center of ellipse.

Gradients, like filters, are defined within the def element. Each gradient is assigned an id. Gradient attributes, such as the colors, are set inside of the gradient tag using stop elements. To apply a gradient to a drawing, set the url value for the fill attribute to the id of the desired gradient.


Text and SVG

In addition to basic shapes, you can also use SVG to generate text, as shown in Listing 17.

Listing 17. Creating text with SVG
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
       <text x="0" y="15" fill="red">I love SVG</text>
</svg>

The code in Listing 17 results in the drawing in Figure 17.

Figure 17. SVG text
Text saying I love SVG

The example uses a text element to create the sentence I love SVG. When you use the text element, the actual text to be displayed is between an opening and a closing text element.

You can display text along numerous axes and even along paths. Listing 18 displays text along an arched path.

Listing 18. Creating text along an arched path
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
 xmlns:xlink="http://www.w3.org/1999/xlink">
        <defs>
                  <path id="path1" d="M75,20 a1,1 0 0,0 100,0"/>
        </defs>
        <text x="10" y="100" style="fill:red;">
                   <textPath xlink:href="#path1">I love SVG I love SVG</textPath>
         </text>
</svg>

The code from Listing 18 results in the drawing in Figure 18.

Figure 18. Text on an arched path
Words saying I love SVG curved along an arc.

In this example, an additional XML namespace xlink is added to the root SVG tag. The path used to arch the text is created inside of the def element so the path does not actually get rendered as part of the drawing. The text to be displayed is nested inside of a textPath element that uses the xlink namespace to refer to the id of the desired path.

As with other SVG drawings, you can also apply filters and gradients to text. Listing 19 applies a filter and a gradient to some text.

Listing 19. Creating text with a filter and gradient
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
xmlns:xlink="http://www.w3.org/1999/xlink">
          <defs>
                    <radialGradient id="grad1" cx="50%" cy="50%"
                           r="50%" fx="50%" fy="50%">
                           <stop offset="0%"
                                style="stop-color:red; stop-opacity:0"/>
                           <stop offset="100%"
                               style="stop-color:rgb(0,0,0);stop-opacity:1"/>
                    </radialGradient>
                    <filter id="f1" x="0" y="0"
                               width="200%" height="200%">
                           <feOffset result="offOut"
                               in="SourceAlpha" dx="20" dy="20"/>
                           <feGaussianBlur result="blurOut"
                               in="offOut" stdDeviation="10"/>
                           <feBlend in="SourceGraphic"
                               in2="blurOut" mode="normal"/>
                    </filter>
          </defs>
          <text x="10" y="100" style="fill:url(#grad1); font-size: 30px;"
                        filter="url(#f1)">
                        I love SVG I love SVG
          </text>
</svg>

The code from Listing 19 results in the drawing in Figure 19.

Figure 19. Text with a filter and gradient
Words I love SVG in a horizontal line with gradiant colors from black to gray, from outer edges working to the center of the text.

Adding SVG XML to web pages

After you create your SVG XML, there are several ways to include it in your HTML pages. The first method is to directly embed the SVG XML into the HTML document, as shown in Listing 20.

Listing 20. Directly embed SVG XML into an HTML document
<html>
     <head>
             <title>Embedded SVG</title>
     </head>
     <body style="height: 600px;width: 100%; padding: 30px;">
              <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
                    <circle cx="100" cy="50" r="40" fill="red"/>
              </svg>
     </body>
</html>

This method is perhaps the simplest, but it does not promote reuse. Remember that you can save an SVG XML file using the .svg extension. When you save the SVG drawing in an .svg file, you can use embed, object, and iframe elements to include it in your pages. Listing 21 shows the code to include an SVG XML file using an embed element.

Listing 21. Include an SVG XML file using an embed element
<embed src="circle.svg" type="image/svg+xml" />

Listing 22 shows how to include an SVG XML file using an object element.

Listing 22. Include an SVG XML file using an object element
<object data="circle.svg" type="image/svg+xml"></object>

Listing 23 shows the code to include an SVG XML file using an iframe element.

Listing 23. Include an SVG XML file using an iframe element
<iframe src="circle1.svg"></iframe>

When using one of these methods, you can include the same SVG drawing in multiple pages and make updates by editing the .svg source file.


Summary

This article covered the basics of creating drawings using the SVG format. You learned how to create basic shapes using the built-in geometric elements, such as line, rectangle, circle, and so on. You also learned how to use the path element to create complex drawings by issuing a series of commands, such as move to, line to, and arc to. The article also explored how to apply filters and gradients to SVG drawings, including text drawings, and how to include your SVG graphics in HTML pages.

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development, XML
ArticleID=789942
ArticleTitle=Scalable Vector Graphics in HTML5
publish-date=01312012