2008 Dec 22
While it is possible to construct an image to view with SVG by specifying every object, frequently groups of objects appear multiple times (perhaps with transforms). This is a macro like facility.
g | use | defs | symbol | image |
This is the grouping element which contains child elements and can have an optional id attribute to give this group a unique name. Each such group can have its own <title> and <desc> to give a text based identity. Any styles applied to the g element will apply to (are inherited by) all its descendents. For example:
<g id="shack" style="fill: none; stroke: green;"> <title>small shack</title> <desc>Small green shack with one door.</desc> <polyline points="0 20, 12 0, 24 20, 24 30, 0 30, 0 20, 24 20"/> <polyline points="12 30, 12 23, 20 23"/> </g>
This element allows a previously defined group (defined with <g> ... </g>) to be reused at a specified location (relative to the group's 0 0 origin). The group to be reused is specified with an attribute of the form xlink:href="URI". The URI can refer to a group in the current document with the syntax #id, for example:
<use xlink:href="#shack" x="32" y="77"/> <use xlink:href="#shack" x="77" y="32"/>
The URI could also refer to a group in another file, e.g. logos.svg#size1
This element is designed to overcome some of the limitations of the <g> and <use> elements, specifically:
All these issues are resolved by the <defs> element by putting grouped objects between that starting <defs> and ending </defs> tag. The contained groups are defined but not rendered until any one of them (which can now be hierarchicaly organized) appears in an instance of <use>. The style issue is resolved by removing one, some, or all the styles from the <g> element and putting them in each instance of the <use> element.
<svg> <defs> <g id="obj1" ...> ... </g> <g id="obj2" ...> ... </g> ... <symbol id="sym1" ...> ... </symbol> </defs> <use xlink:href="obj1" style="..."/> <use xlink:href="obj1" style="..."/> <use xlink:href="obj2" style="..."/> <use xlink:href="sym1" style="..." width="64" height="128"/> </svg>
Unlike the <g> element a <symbol> element is not rendered and hence does not have to be contained in a <defs> element (although it typically is). Another important difference is symbols can optionally specify viewBox and preserveAspectRatio attributes for the viewport defined by a <use> element (see example above).
It is important to note that width and height attributes in a <use> element are ignored for a <g> but are applied for a <symbol>.
The <image> element can define a viewport for either an entire SVG file or a raster file (currently only JPEG or PNG), for example:
<image xlink:href="stuff.jpg" x="64" y="80" width="120" height="240"/>