Self-contained dynamic charts

By on 15 Jun 2015

Category: Tech matters

Tags:

Blog home

Image from Wikipedia.

Here at APNIC, I often use Scalable Vector Graphics (SVG) for dynamic charts. Coupled with the Data-Driven Documents Javascript library, these technologies allow for interactive and responsive graphics to help bring data presentation to life. In this post, I’d like to share a technique I use to make embedding dynamic charts simpler and more effective.

One of the challenges when producing a chart is knowing how much screen space will be available when the chart is finally displayed to a user. There is not only the concern that different devices have different screen sizes, but also an embeddable chart has no way of knowing ahead of time how much space it will be allocated on a web page it’s embedded into.

SVG helps solve this issue with the concept of a view box. The view box specifies an internal coordinate space for the SVG element that is translated automatically to the SVG’s real size, allowing SVG elements (and code to manipulate them) to have precise relative positioning no matter what size the container is. Coupled with the ability to preserve aspect ratio, this frees up an SVG image from the specifics of screen dimensions.

This internal coordinate space is applied whenever no units are given, so a <rect x="10" y="10" width="50" height="50"/> will have a position and size relative to the view box of the SVG. Providing units for any measurement will use the absolute size of the SVG image’s context, so a line can be given a stroke width of 0.5px and look correct at any scale.

An SVG image can be loaded into a web page either as an image (<img src="example.svg">) or as an object (<object data="example.svg"></object>). In both cases, CSS or HTML attributes can be used to give it a size on the page, while the SVG image file itself defines its view box and aspect ratio needs. If height is auto (the initial value) then the browser will choose a height to maintain the original aspect ratio specified in the view box.

Here’s where it gets more interesting: the SVG specification also allows scripting to be defined inside the image’s document. Browsers will only allow this when the SVG is embedded using object, such that it’s more apparent to a web page author that the image they’re embedding potentially contains more behaviour than a static image is expected to contain, but all modern browsers fully support this behaviour, including the most common mobile browsers.

Putting all this together, you can embed an SVG object into HTML easily and portably, and have behaviour inside the rendered SVG. Here is a trivial example which charts how many mouse movements are tracked each second.

Rate this article

The views expressed by the authors of this blog are their own and do not necessarily reflect the views of APNIC. Please note a Code of Conduct applies to this blog.

Leave a Reply

Your email address will not be published.

Top