SVG - Super Vector Graphics

, Alexander Goedde

SVG is the true native Web graphics format - not just scalable, but integrated into the DOM.

Part 1 of a series

Your browser doesn't have JavaScript enabled. You won't be able to use some interactive elements on this page.

Additionally, it is not possible to detect whether your browser has support for SVG.

If the images are missing, it may be due to the lack of such support.

Your browser does not support SVG. Images used to illustrate this post will not display.

Please use a modern browser to view the images.

This is the first part in a series of blog posts on SVG:

  1. SVG - Super Vector Graphics: basics, advantages, and handling within the browser
  2. Preprocessing SVGs for the Web in 3 automated steps: Setting up cross-browser display, optimization & compression, creating PNG for fallback solutions
  3. Falling back from SVG: A SVG-first fallback solution for the few problematic browsers

SVG is vectors in XML

SVG (Scalable Vector Graphics) is a vector image format. Unlike bitmap image formats such as JPG or PNG, it does not consist of a fixed set of dots, but of shapes and their attributes.

This means that it scales perfectly to any desired size and resolution.

Scale me any way you like!

SVG is essentially markup and associated styles - all stored as an XML. The SVG above consists of the following markup:

   <?xml version="1.0" encoding="UTF-8" standalone="no"?>
   <svg id="mySVGCircle" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns="http://www.w3.org/2000/svg" height="130" width="130" viewBox="0 0 130 130"
   version="1.1">
    <g id="layer1" transform="translate(-165.93 -333.58)">
     <path id="theCircle" d="m342.86 330.93c0 70.219-38.376 127.14-85.714 127.14-47.339 0-85.714-56.924-85.714-127.14 0-70.219 38.376-127.14 85.714-127.14 47.339 0 85.714 56.924 85.714 127.14z"
     transform="matrix(.69666 0 0 .46966 51.787 243.15)"
     stroke="#f60" stroke-width="10" fill="#ffd42a"/>
    </g>
   </svg>
   

Depending on the method for adding this to the page, the SVG DOM is then accessible from JavaScript and via CSS.

Perfect at any size

SVG images essentially consist of lines, curves and shapes as their basic elements. These elements are drawn at the desired scale, i.e. rendered at the target size and at the resolution of the target display. They can be resized any way required and they are always rendered sharp. SVGs are as sharp as the target display and scale factor will physically permit.

You no longer have to care what the target size is, how much a user might zoom in, or what the pixel density of the target is. The still standard desktop 100dpi, 200dpi, or future densities of 1000dpi, it makes no difference: SVGs are future-proof by their very nature.

Scriptable images

Since, with most ways of using them, SVGs are accessible as part of the DOM, we can access them via JavaScript. Scripting can principally do two things here:

  • Change the appearance and content of the SVG, e.g. set colors or add elements.
  • Add triggers to elements of the SVG, e.g. add a 'click' handler.

To change the color of the circle, all we need to do is

   document.getElementById("theCircle").style.fill = "red";
   

and our circle turns red.

Adding triggers is no different to handling normal HTML elements. With our circle, we'd just do

   document.getElementById("theCircle").addEventListener("click", function() {
      console.log("clicked")
   });
   

to add a console log each time the circle is clicked.

Combine the two, and you have a circle which can be clicked to change its color:

Click me to change my color!

Your CSS can style your images

Above we change the fill color by changing an elements style property. Similar to inline styles in HTML, this has its uses, but quite often we want to abstract stylings.

Since the SVG is part of the DOM, we can apply CSS rules.

If we add a class to an element in the SVG

   document.getElementById("theCircle").setAttribute("class", "changedColors");
   

a corresponding CSS rule

   .changedColors {
      fill: red;
      stroke: green;
   }
   

applies, the fill color of the circle is now red, and the border of the circle is green.

Click me to change my styling!

CSS rules apply as they normally do, but we may have to address different properties, e.g. the 'fill' and 'stroke' in the above example.

A lot of the properties we're used to work as normal though, e.g.

   .hidden {
      visibility: hidden;
   }
   

when applied results in just that: a hidden circle.

Just for completeness' sake: Click me to make me disappear!

Creating SVGs

While it's possible in principle to construct SVGs on paper and author them in a text editor, there are, of course, graphics editors which help with the task.

The easiest way to try things out is to use Inkscape, a free vector graphics editor which uses SVGs as its native image format.

Commercial vector graphics editors such as Adobe Illustrator and CorelDRAW can also export SVG.

Existing vector graphics images can usually be converted, and depending on the image content, it may even be possible to convert bitmap images.1

Browser support

As with any technology on the web, the big question is browser support. By web standards, SVG has been around since forever (1999), and a quick check at caniuse.com shows only IE < 9 and Android < 3.0 as entirely lacking support.

SVG is a complex standard, and both how far it is supported, and details of the implementation of support vary across browsers, e.g.

With the examples above, it would have been much preferable to add and remove classes doing

   document.getElementById("theCircle").classList.add("changedColors");
   

This works fine in some browsers, e.g. Chrome and Firefox, but not in Internet Explorer 9 - 11 or the stock Android browser (4.1 - 4.3).

Image sizing is another aspect, where the Android browser expects both an image width and height to be defined, but others scale proportionally with just the width set.

So support is not strictly universal and consistent, but it is strong enough for a lot of use cases. Everything you need for normal, clean graphics as a replacement for bitmap graphics works in all modern browsers.

For other, more advanced functionality, you'll have to test on a case-by-case basis, and consider the importance of what you're doing for the functionality of your page or Web application.

While you can't use advanced SVG features for basic functionality for a website which addresses the general public, for enhanced functionality it may already make sense. For somebody targeting solely tech-savvy users with the newest browsers, you may be OK to implement core functionality using SVG.

We'll take a look at a fallback solution to bitmap graphics, for cases where you just use SVG as regular images, in a future post in this series.

Using SVG in the browser

The SVG markup can be added directly to the HTML in most browsers.2

It's also possible to use SVGs from external files. In this case, there are four variants for including it in a page, as

  • an image: <img src="circle.svg">
  • an embedded image <object id="object" data="circle.svg" type="image/svg+xml"></object>
  • an element to be handled by a plug-in <embed id="embed" src="icon.svg" type="image/svg+xml">
  • an IFrame <iframe id="iframe" src="icon.svg"></iframe>

Among these, the <img> doesn't require any change in how you normally use images, is easiest to scale across browsers, and will in many cases be the simplest solution if you want some kind of fallback to bitmap images. There is, however, one major drawback: The SVG DOM is not accessible here.

In all other cases, access to the SVG DOM is easy:

      var svgObject = document.getElementById("object").contentDocument;
      var svgIframe = document.getElementById("iframe").contentDocument;
      var svgEmbed = document.getElementById("embed").getSVGDocument();
   

where the variables then contain the DOM.

To do the above adding of an event listener, the only change is to start with the respective object instead of the document, e.g.

   svgObject.getElementById("theCircle").addEventListener("click", function() {
      console.log("clicked")
   });
   

Start using SVG!

The advantages of SVG can go far beyond their scalability and resolution independence. SVGs are the Web graphics format because of the possibilities that integration into the DOM offers. While they've been around for a long time, at times they still feel, and handle, like cutting edge technology.

With the above information, you should be ready for your own experiments, to explore what SVGs can do for you in your specific application - or even how they can change what you do in your application.

Footnotes:

1. See caniuse.com.

2. Some software, such as CorelDRAW comes with tracer software which attempts this, or you can use an online service such as Vectormagic. For simple images such as a lot of logos, with files at sufficiently high resolutions, the results can be very usable.

Find out how to create component-based, real-time apps for the Web, mobile and IoT in less time and with less complexity using

Crossbar.io name

Crossbar.io is an open-source Unified Application Router created and supported by Tavendo

Learn more

About

Tavendo provides open-source middleware that helps developers create next-gen applications in less time and with less complexity.

We are authors and maintainers of WAMP (Web Application Messaging Protocol), Crossbar.io (Unified Application Router) and Autobahn (Real-time Web Framework).

us on Twitter

Stay Informed

Sign up for our newsletter to stay informed of new product releases and features:

Professional Services

Tavendo offers consulting, support and custom development for Crossbar.io and Autobahn based solutions.

Get in contact and send us an Email describing your project, issue or question.

Recent posts

Atom Feed

Search this Site