SVG Chart with API

Excerpt

Connected via API.

In a previous page we have seen how SVG+JavaScript can be combined to create a compact, animated SVG graphics.

Here the same approach is used: All functionality comes with the SVG file but it can be controlled by the script on the page where the SVG is embedded. The handover point between page and SVG object is defined by the contract known as API (a Programming Interface).

Playground

How it works

1. Create the Chart

To create the Gauge a simple object tag is required:

<object id="testChart" data="chartgauge.svg" type="image/svg+xml" style="..."></object>

2. API access

APIs are always exposed by a server (here the SVG object) and accessed by the client (script on the page) so we need to find a place in the technology to implement this API. Here I use the document of the SVG element.

In the SVG implementation you can find:

// expose API functions.
document['api'] = {
  setOptions: function (opts) { ... },
  draw: function (value) { ... },
  clear: function () { ... },
}

The api javascript object is available on the document of the SVG element with a set of functions that can be called.

To access this from the page is is required to find this object inside the <object> element using the following code:

var chartAPI = document.getElementById('testChart').getSVGDocument().api;

3. Configuration

To setup the gauge in the colors and segments as we need it a descriptive objects can be passed to the setOptions function. The value to be displayed can be changed using the draw function.

var gaugeOpts = {
  title: "Room Temperature",
  units: "°C",
  minimum: 5,
  maximum: 45,
  segments: [
    { value: 18, color: '#aaaadd' },
    { value: 22, color: '#33cc33' },
    { color: '#ff4444' }
  ]
};
chartAPI.setOptions(gaugeOpts);

4. Set Values

These buttons above the chart change the current value by calling the draw() function:

chartAPI.draw(21.7);

Comment

One problem is within scripting inside SVG as the script may not contain pointed brackets like < and >. The browser will complain.

You either have to rewrite them with &lt; in the code what makes the code worse or use a <![CDATA[ ... ]]> around the script as you can see in the CSS reference material and in the implementation.

This is a example on how to extend plain SVG with functionality. Maybe Web Controls also work ? - However is is quiet useful to include a tag that contains all required functionality.

Maybe in the future the editors and the browsers can treat both the same way with full functionality.

See also

Tags

JavaScript