SVG (Scalable Vector Graphics) is a modularized language for describing
two-dimensional vector and mixed vector/raster graphics in XML. It is a
W3C Recommendation currently at version 1.1.
SVG is a language for describing two-dimensional graphics in XML.
SVG allows for three types of graphic objects: vector graphic shapes
(e.g., paths consisting of straight lines and curves), images and text.
Graphical objects can be grouped, styled, transformed and composited into
previously rendered objects. The feature set includes nested transformations,
clipping paths, alpha masks, filter effects and template objects.
SVG is implemented natively in Firefox from version 1.5, Opera from version 8.5,
Safari from version 3.0, and in IE from version 9.0.
Not every SVG construct is supported by these implementations.
For IE prior to version 9, you need one of the SVG browser plugins to render the documents
(such as the Adobe SVG viewer
or the Renesis Player).
You also need to use an older version of this plugin (before 1.5.0),
and provide a blank SVG document that is initially loaded to register
itself with the plugin and allows access to its internal structure. This is the
blank.svg document. Because of this requirement, you must wait
for the document to be loaded before accessing the SVG instance and using it.
Use the onLoad setting to be notified when loading is complete.
The callback is not necessary for the other browsers, but its use provides
a consistent access pattern for them all.
Processed divisions are marked with a class of hasSVG
and are not re-processed if targeted a second time.
Extension Plugins
As well as the basic SVG functionality, the plugin allows for extending its
abilities via additional packages. In this way you can avoid loading code
that you are not going to use. Most extensions add an entry point object to
the SVG manager object, returned by $(selector).svg('get'),
from which you can access its functionality.
Currently the following extensions are available:
Package
Entry point
Functionality
jquery.svganim.js
-
Support for jQuery animation of SVG attributes.
Since 1.1.0.
jquery.svgdom.js
-
Support for jQuery/SVG DOM compatibility.
Since 1.4.0.
jquery.svgfilter.js
svg.filter
Support for SVG filter element and filter definitions.
jquery.svggraph.js
svg.graph
Support for basic graphing using SVG.
jquery.svgplot.js
svg.plot
Support for plotting functions using SVG.
Since 1.3.0.
To use these extensions just load them after the main
jQuery SVG Javascript in the head section of your page.
Each extension registers itself with the SVG framework as shown,
indicating the name of its entry point and the class (function)
that encapsulates its functionality:
$.svg.addExtension('graph', SVGGraph);
Attach an SVG canvas and retrieve the SVG instance as before.
Then access the new functionality through its entry point:
These examples are taken from the
SVG 1.1 specification
to show how they might be implemented using this package.
Select one of the examples taken from the SVG specification
that demonstrates how the functionality might be produced using this package.
Both the original SVG document and the jQuery SVG code are shown below.
SVG Source Document
SVG jQuery Code
SVG Load
The SVG component may be updated with inline SVG elements, be cleared of all content,
or be loaded with external SVG documents. In the latter case, you may pass additional
settings to add to any existing content (addTo: true) or automatically
clear it first (addTo: false - the default).
You can also specify a callback function (onLoad: loadDone) to
be notified when the external document (loaded asynchronously) has completed.
The function receives the current SVG wrapper object as a parameter,
and an additional message parameter if there was an error.
The this object is the SVG container division.
<svg id="svginline">
<g>
<rect width="350" height="50" x="20" y="90" fill="blue"></rect>
<text x="40" y="120" fill="white" font-weight="bold">
This came from an inline SVG fragment</text>
</g>
</svg>
$('#loadExternal').click(function() {
var svg = $('#svgload').svg('get');
svg.load($('#loadURL').val(), {addTo: $('#addTo')[0].checked,
changeSize: false, onLoad: loadDone});
resetSize(svg);
});
/* Callback after loading external document */
function loadDone(svg, error) {
svg.text(10, 20, error || 'Loaded into ' + this.id);
}
SVG Attribute Animations
By adding the jquery.svganim.js extension
to your page you can easily animate several of the attributes of the
various SVG elements using the standard jQuery
animate function.
All attributes must be prefixed by 'svg' to identify them as SVG settings
and are written in camelCase, e.g. svgStrokeWidth.
Many of the values may be expressed as exact pixels or as percentages.
You can also use the '+=' or '-=' prefixes for relative values.
Then access the extra functionality via the
graph object within the SVG root. As well as the series and their formatting,
you can control the graph title, axes, gridlines, labels, and legend.
Then access the extra functionality via the
plot object within the SVG root. As well as the functions and their formatting,
you can control the plot title, axes, gridlines, labels, and legend.
$('#svgplot').svg(initPlot);
var plotZooms = [[-2, 2, -1.5, 1.5], [-10, 10, -10, 10]];
var chartAreas = [[0.1, 0.1, 0.95, 0.9], [0.2, 0.1, 0.95, 0.9],
[0.1, 0.1, 0.8, 0.9], [0.1, 0.25, 0.9, 0.9], [0.1, 0.1, 0.9, 0.8]];
var legendAreas = [[0.0, 0.0, 0.0, 0.0], [0.005, 0.1, 0.125, 0.5],
[0.85, 0.1, 0.97, 0.5], [0.2, 0.1, 0.8, 0.2], [0.2, 0.9, 0.8, 0.995]];
function initPlot(svg) {
svg.plot.noDraw().title('Functions', 'blue').
addFunction('Sine', Math.sin, 'blue', 3).
addFunction('Cosine', Math.cos, [-Math.PI, Math.PI], 20, 'red', 3).
addFunction('Decaying', decay, 'green', 3).
format('ivory', 'gray').
gridlines({stroke: 'gray', strokeDashArray: '2,2'}, 'gray');
svg.plot.xAxis.scale(-1, 3.5).ticks(1, 0.2);
svg.plot.yAxis.scale(-1.5, 1.5).ticks(1, 0.2);
svg.plot.legend.settings({fill: 'lightgoldenrodyellow',
stroke: 'gray'});
svg.plot.status(showPlotStatus);
}
/* Plot a new function with the selected options */
$('#plotIt').click(function() {
var plotZoom = parseInt($('#plotZoom').val(), 10);
var plotEqual = parseInt($('#plotEqual').val(), 10);
var plotLegend = parseInt($('#plotLegend').val(), 10);
var svg = $('#svgplot').svg('get');
svg.plot.noDraw().
legend.show(plotLegend).area(legendAreas[plotLegend]).end().
xAxis.scale(plotZooms[plotZoom][0], plotZooms[plotZoom][1]).end().
yAxis.scale(plotZooms[plotZoom][2], plotZooms[plotZoom][3]).end().
area(chartAreas[plotLegend]).equalXY(plotEqual).redraw();
resetSize(svg);
});
/* Decaying sine wave */
function decay(x) {
return Math.exp(-0.4 * x) * Math.sin(x);
}
function showPlotStatus(label) {
$('#svgplot').attr('title', label);
}
Mixture of Graphs/Plots/etc.
You can combine graphs, plots, and other SVG elements in the one document.
A default container (embedded <svg>) is created for each of a graph
and a plot. You can change the settings for these or specify a new
container and size and position it appropriately.
The SVG DOM is different to the HTML DOM for which jQuery was designed.
In particular, any attributes that can be animated are stored as objects
instead of plain strings. This includes the class attribute.
Thus, jQuery's functions that work with classes don't work on SVG nodes.
To overcome this problem you can use the jQuery SVG DOM extension.
Add the extension in the head section of your page.
Then just use jQuery's class and attribute functions on SVG nodes as well:
addClass, removeClass, toggleClass,
hasClass, attr, and removeAttr.
Use the power of jQuery to select nodes in the SVG document with this
extension. Provide the SVG root element as the context for your selections:
$(selector, svg.root())...
Unfortunately, for older versions of IE (before 9.0), there are some small modifications
needed to the base jQuery code that cannot be overridden in the extension.
These modifications are not needed for IE9+ and plugin 1.5.0+.
Since older versions of IE require the ascynchronous loading of a seed SVG document,
you should not try to access the SVG components immediately after attaching this plugin
to a division. Instead, make use of the onLoad callback to ensure that
the SVG component is ready when you want to use it.
Since SVG is XML, you can use the power of jQuery on it as well.
Retrieve the SVG wrapper as usual, then work with respect to its root element.
For example, to change the line colour for all circles in a container:
var svg = $('#mycontainer').svg('get');
$('circle', svg.root()).attr('stroke', 'red');
Note, however, that jQuery is designed for the HTML DOM and that the
SVG DOM is different and some things do not work. For example, the class
names in SVG are actually objects rather than the simple strings of HTML,
since they can be animated. This means that the class selector of jQuery
doesn't work. The SVG DOM extension adds SVG support for the class
and attribute functions of jQuery and for jQuery selectors over SVG nodes.
You can also access jQuery from JavaScript embedded within the SVG.
First, you need to break out of the SVG document back into
the containing page, and then use jQuery as usual.
For example, in response to a click event, change the
colour of all circles in the document:
var jQ = (window.parent ? window.parent.jQuery : window.jQuery);
var svg = jQ(event.target).parents('svg');
jQ('circle', svg).attr('fill', 'blue');
You can even use this plugin from within a standalone SVG document.
After loading the jQuery and plugin code, you need an onload
handler to initialise the SVG wrapper, passing it a reference to the root
SVG element and an object providing the expected width and height.
The example below shows all of this and draws a plus sign
in the top-left corner of the canvas.
A Java Web application that generates SVG data model
diagrams for any database with a JDBC driver.
jQuery SVG helps manage the diagram on the Web page.
In this application you can create SVG banner graphics which are also
exported as raster graphics. You can choose several fonts and cliparts
and you can drag around and position the elements whereever you like.
Most of the functions were created with the help of the plugin.
To add another example, please contact me (wood.keith{at}optusnet.com.au)
and provide the plugin name, the URL of your site, its title,
and a short description of its purpose and where/how the plugin is used.
Quick Reference
A list of available fields and functions. For more detail see the
documentation reference page.