BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage Articles Towards a Resolution-Independent Web with SVG

Towards a Resolution-Independent Web with SVG

Leia em Português

Bookmarks

The Web Platform has gone a long way since HTML5 was first made popular and people started looking into JavaScript as a language that could do build complex apps. Many APIs have emerged and there is an abundance of content out there about how the browser can leverage all this.

This specific article series will go a step further and focus on how these powerful technologies can be leveraged in practise, not to building cool demos and prototypes, but how real practitioners use them in the trenches. In this (post)HTML5 series, we'll go beyond buzzwords and get practical insight from experts about what has actually worked for them. We'll also talk about technologies (like AngularJS) that go a step further, and define the future of how the standards and web development will evolve.

This InfoQ article is part of the series “Next Generation HTML5 and JavaScript”. You can subscribe to receive notifications via RSS.

 

This article examines the advantages of using Scalable Vector Graphics (SVG) as the preferred format for the graphic assets of any web or mobile web project.

The aim here is not to deter designers and developers from the proven method of using raster formats (PNG / JPEG) but rather to showcase how usage of SVGs can enhance the workflow of the two main lifecycles of any web project: The design and the development stage.

Designers

Ideal for resolution-independent user interface icons

At the time of this writing, the “Flattening of Design” is an unavoidable meme. Microsoft is applying their Modern Design approach to all their software as well as mobile device user interfaces. With the advent of iOS7, Apple has masterfully substituted their clever skeuomorphic principles in favour of clear and flat design guidelines. Not to be left behind, Google is pushing for its “Material Design” visual language to be used everywhere, from Android apps to websites.

The “Flattening of Design”: Glows, drop shadows and pseudo-3D skeuomorphism is devolving into simple shapes.

With complex pseudo-3D UI backgrounds devolving into primitive colours and sculpted buttons turning flat - both approaches easily implemented with html elements styled with CSS - the focus of UI design is moving towards typography, layout and icons.

The main advantage of SVG - rightfully advertised all over the web - is its scalable nature. When preparing an icon, a designer can stop worrying about “how it will look” in different dimensions or on mobile devices with different pixel densities, and focus solely on making the asset look great.

With SVGs there is no need to export two different raster assets for retina and non-retina displays. As a matter of fact, there’s no need to worry at all about the pixel density of any device, especially given the (sometimes absurd) non-standardised nature of it, but focus rather on the artwork itself. Once an icon is ready, the designer exports a single SVG file - directly from Illustrator - which can be resized at whim by the developer with no loss of quality.

One less step in the designer’s workflow. No need to export @2x (or @3x soon) version of an asset. The SVG asset can be scaled at whim by the developer with no loss of quality.

Browser scaling is getting better and better, even on small dimensions

A common design challenge for the slightly-more-obsessive-compulsive-than-normal designer: Working in Photoshop, an icon might look great in the finger-friendly dimensions of 44x44 pixels, but try resizing it down to 24x24 or 16x16 and the bicubic interpolation introduces-anti aliasing artifacts which might result in a blurry image. Even with clever algorithms such as the “sharp” bicubic interpolation available in the latest versions of Photoshop, many designers end up drawing from scratch the smaller image assets (interface icons, favicons etc.) to achieve clarity.

With SVGs, the above scenario is partially mitigated by the fact that browsers scale (and consequently rasterize) SVG assets very well. This is especially true for higher display densities such as the latest generation mobile devices.

Browser scaling is getting better. In certain cases the browser scaling ends up looking better even than the advanced interpolation methods of Photoshop.

For optimal results in these dimensions, a designer can easily “package” all SVG assets into an icon font (see Developer section 5 below for more details) and thus leverage the subpixel hinting capabilities of the various operating systems, resulting in icons sized at 12 or 14 or 16 pixels that look crystal clear and razor sharp, even on old IE browsers.

SVG elements can be “handcrafted” to reduce complexity and file size.

Optimizing a JPEG image is a one-way process of reducing a quality slider while trying not to lose too much information. For PNG and GIF assets, the designer has slightly more control due to the ability to specify a restricted palette and thus reduce the information encoded in the file.

With SVG, the meticulous designer can opt to use primitive shapes, reduce the number of vertices in the shape elements as well as have text embedded inside the SVG instead of converted to outlines, all of which can result in a less complex SVG file, and smaller in size.


Illustrator’s “Simplify” in action. The vertices that make up a vector path can be reduced with minimal loss of precision, ending up in a smaller SVG file. 

For even more optimization, extraneous SVG properties such as comments, ids, or redundant grouping tags (<g>) can be removed as well by editing directly the SVG code.

Better Open Source tools

For Photoshop (and perhaps Fireworks or Sketch), the Open Source world offers the Gimp editor. Gimp is a valuable tool with a vibrant community, yet when contrasted with any of the aforementioned pieces of software, it is inferior in several areas. Substituting Photoshop with Gimp is not an easy task, and it usually results in a very convoluted workflow.

For vector artwork however, Inkscape is a professional-grade open source alternative to Adobe’s Illustrator, enabling designers to create and edit vectors with a plethora of tools and procedures, similar to what they are used to with Adobe’s offering. Many of the “everyday” actions of working with vectors can be done in Inkscape as well, such as boolean operations to combine shapes, path simplification, dynamic offsetting of paths, editing subpaths and much more.

Developers

Resolution independence and reusability

For displays with higher densities such as retina screens and mobile devices, the need for “@2x” high-res assets goes away. With the proper meta tags and with the asset dimensions specified in the CSS file, a developer has full creative control when it comes to resizing the asset, without the need to push back to the designer for variations of the same file.

There is something exhilarating in the fact that a single file, e.g. company-logo.svg, can be used in various places on a user interface, with the dimensions being controlled by CSS or by width / height attributes, and with the resulting asset looking crystal clear irrespective of how much it is scaled (or rotated).

Animation

SVGs animated with CSS3 retain sharpness and clarity throughout the animation duration. A couple of examples are shown below but please note that the low frame rate of the animated gif does not do justice to the GPU-accelerated smoothness of the finished effect:

 

For a live demonstration visit the homepage of www.adzuna.co.uk and focus on the textfields, or click the “more” links in the bottom lists.

But that is only the beginning. The structured XML syntax of SVG enables a developer to programmatically select and animate individual elements of an SVG file to create scripted animations, banners, ads etc. CSS-Tricks has an excellent step by step tutorial for creating an animated banner in SVG format, and showcases how - when placed inline - individual elements of an SVG image can be manipulated with CSS to follow a certain script, resulting in an animated banner similar to what the web was used to when Adobe’s Flash was the industry standard for animated advertisements.

Interactivity

The potential of SVG as a replacement to Adobe’s Flash does not stop with animation. SVG content can be interactive, with events such as click, mousedown, mouseup (and a few interesting ones such as SVGZoom / SVGResize) available to the developer to programmatically listen for and respond to, using Javascript.

This opens up a list of possibilities such as interactive infographics and enterprise-strength charting solutions.

Going further, the developer can use helper libraries which facilitate drawing, manipulation and interactivity, with some of the top candidates being RaphaelJS, D3.js and Snap.svg. With libraries like these, complex animated and/or interactive presentations that were previously only in the domain of Flash are now possible, with several examples available for inspiration, from NY Times’s custom tree structure for political analysis of the Obama / Romney campaigns, to Hamiltonian Graphs, Force-directed graphs, zoomable interactive maps from the 2001-2010 Argentinian Census and countless more.

Inline use

Going back to the implementation details: The two standard approaches to using image assets on a web project are by means of an <img> tag, and as background images for (usually block-level) elements. Since SVG is XML, a third possibility is now available to developers: Inline use.

SVG code can be placed directly into the HTML. Older browsers will simply ignore it, newer browsers will render the vector asset. Asset is now “reacheable” by CSS (#wa_i) and Javascript (document.getElementById(‘wa_i’)).

With HTML5, the <svg> element can be placed directly into the source HTML of the page. The advantage here is that the <svg> element, as well as its children elements, can be controlled with CSS.

Apart from size and position, fill and stroke colors can also be manipulated, even animated. Furthermore, certain SVG-only attributes (such as stroke-dasharray and stroke-dashoffset) can be manipulated from within the CSS file resulting in some very interesting possibilities for animation such as the line animation effect.

More ways to “sprite”

With raster assets, a classic optimisation approach for reducing HTTP requests is to combine several images into a single “sprite” (usually PNG) and use the background CSS property to style several different HTML elements with the same sprite.

With SVG assets, two extra interesting possibilities are now available to developers:

  1. Classic sprite approach
    An SVG asset with fixed dimensions can contain multiple sub-elements, placed in specific coordinates. The developer uses the asset as a background-image and repositions it to show the element in need.
  2. Inline grouping approach
    With inline placement, the ability to control the display of sub-elements with CSS enables a developer to create an SVG “bucket” of assets, with each group being an element such as an icon. ID’s can be assigned to individual groups, and by changing the display property of each group, the developer chooses what to hide and what to show. This technique works really well with interface elements that have the same dimensions, such as the icons for a user intercace.
  3. Packaging in an icon font
    The developer also has the option to “package” several SVG assets together into an icon font. Browser support is excellent (even IE6) and the subpixel hinting engines of modern browsers make even small sizes look crystal clear and sharp. Even better, there a multiple online icon font generators available that make the (somewhat annoying) packaging process a breeze.

Comparing versions of the same asset

The SVG format, by its virtue of being essentially a text file, presents the developer with the interesting possibility of not only comparing an asset visually, but also doing a file diff to establish which parts of the SVG have changed.

In the case of large and complex SVG files, such as an infographic, text comparison is great in establishing what parts of the asset have changed in a newer version.

Further reading

For developers, this authors’ personal preference is Chris Coyers (or CSS-Tricks fame) Compedium of SVG Information. A “mega list” of links to SVG resources - split by logical sections - the compedium is the definitive starting point for anyone interested in SVG.

For designers, Todd Parkers’ massive “Leaving Pixels Behind” presentation is the best possible introduction, packed with animated gifs showcasing the Illustrator to SVG workflow.

Falling back for older browsers

At the time of this writing, Internet Explorer 8 is still - unfortunately - something developers need to address. When this need is combined with the fact that pre-v3 Android Browsers lack support for SVG, a fall back solution must be implemented.

For developers, Modernizr is the tool of choice here. Including the Modernizr library as an external <script> in the <head> of any web project will add the appropriate classes to the <html> element of said document on page load. It is then a matter of adding a few extra definitions to the CSS stylesheet to replace background SVG images with raster fallbacks, or in the case of inline SVGs or SVGs placed in <img> tags, show “helper” tags which contain the raster fallbacks and are by default hidden.

The challenge here is to not have to push back to the designer to export fallback assets since this invalidates their “export only one SVG asset” advantage mentioned above.

Fortunately, automation tools such as Grunt and specifically Filament Group’s Grunticon are here to help. In short, Grunticon operates on a folder of SVG assets and it outputs a list of fallback PNG files along with a fallback CSS file which references these PNG images. For command-line gurus, Inkscape can be used as part of a shell script to also convert SVG files to any format.

Summary

The advantages of using vector graphics on the web are now more numerous that the disadvantages. With excellent browser support and automated fall back solutions to support older browsers, it is this authors belief that “future-proofing” a UI with resolution-independent vector graphics is the way to go forward.

About the Author

Angelos Chaidas is currently the senior frontend developer at Adzuna, the international job search engine. He started his career in 2000 as a designer + full-stack PHP developer but has focused in Frontend and Javascript development for the last 8 years. He loves mobile UX + UI design, is passionate about web optimisation and has spoken locally at a few Javascript events. You'll find his random twitter thoughts at @chaidas.

The Web Platform has gone a long way since HTML5 was first made popular and people started looking into JavaScript as a language that could do build complex apps. Many APIs have emerged and there is an abundance of content out there about how the browser can leverage all this.

This specific article series will go a step further and focus on how these powerful technologies can be leveraged in practise, not to building cool demos and prototypes, but how real practitioners use them in the trenches. In this (post)HTML5 series, we'll go beyond buzzwords and get practical insight from experts about what has actually worked for them. We'll also talk about technologies (like AngularJS) that go a step further, and define the future of how the standards and web development will evolve.

This InfoQ article is part of the series “Next Generation HTML5 and JavaScript”. You can subscribe to receive notifications via RSS.

Rate this Article

Adoption
Style

BT