HTML and CSS Reference
In-Depth Information
Beyond the Basics
SVG is a large specification that includes a large number of additional pieces including Animation, Filters, Clip-
ping, Masking, and Compositing that aren't going to be used in this chapter. However, there are a number of
cases in which these features might be useful in game development, so take a moment to look through the full
SVG specification if you are interested in learning more: www.w3.org/TR/SVG .
If you haven't taken a look at the specification yet, you should become familiar with it because going straight
to the source is usually the best way to get answers quickly (often quicker than searching Google).
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 sec-
tion 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 docu-
ment.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 docu-
ment.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 and pass in the SVG namespace:
var SVGNS = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(SVGNS,"svg");
This element is now a normal SVG element that will render elements inside of it as proper SVG elements.
This pattern continues if you need to create other SVG elements. For example, to create a <rect> element,
you would need to use createElementNS as well:
var SVGNS = "http://www.w3.org/2000/svg";
var rect = document.createElementNS(SVGNS,"rect");
Adding that <rect> to the <svg> element can be done using the standard appendChild() command:
svg.appendChild(rect);
Search WWH ::




Custom Search