Working with SVG from JavaScript

As you might expect, SVG elements have an interface exposed via JavaScript that enables you to manipulate any SVG properties. Unfortunately, the method to do this is different than normal DOM elements, so jQuery can’t do its normal thing. There are jQuery plug-ins for extending jQuery with SVG support, such as Keith Wood's jQuery SVG: http://keith-wood.name/svg.html.

However, rather than introduce another dependency, this section examines how to add and manipulate SVG documents directly. Doing so ensures that when SVG support is added to the Quintus engine in the next section that the engine doesn’t get bogged down performance-wise with too many layers of abstraction. (The CSS3 RPG from the last chapter similarly used DOM methods directly when there was a performance advantage to do so.)

Creating SVG Elements

The general mechanism to create a new DOM node without using jQuery is to use the document.createElement method. Using this method to create an <svg> element on the page unfortunately won’t quite do the trick. It will add an element called <svg> to the page, but that element will act just like a normal DOM element and won't have any SVG-like properties.

To create an SVG element dynamically, you need to use the less well-known document.createElementNS, which creates an element within the specified name space.

In the case of SVG, the namespace is defined as:

http://www.w3.org/2000/svg

To create an SVG element, you need to call createElementNS ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.