apike.ca

Layering Shapes in SVG

SVG draws shapes based on the order that they appear in the document object model (DOM). The DOM is initially generated from the XML.

This is a different from how the DOM is treated in HTML. In HTML, the position in the DOM relates to the position on the page. In SVG, it changes the layering. Positioning is instead given using attributes like 'x' and 'y' or transformations. There is no explicit "z-index" like there is in HTML.

The type of ordering used is referred to as the painters model. As a SVG document is rendered, each element is painted over the existing shapes in the order they are found in the DOM. To change how things are layered, the order of shapes in the DOM must be altered. In a static file, this can be accomplished by changing the source XML. JavaScript can be used to dynamically change the DOM.

1
2
3
4
5
6
<rect x="0" y="0" width="50%" height="100%" fill="url(#checkerPattern)" />
<g id="group1" fill="green" opacity="0.9" >
    <rect x="20" y="20" width="100" height="100" opacity="0.5" />
    <rect x="80" y="80" width="100" height="100" fill="darkorchid" />
</g>
<text id="orderTxt" x="20" y="140" fill="black" stroke="white" stroke-width="2" font-size="80">SVG</text>
Code 1. The order of the tags in the example.

A layer is just a grouping of elements. Therefore, the grouping element can double as a layer element. In fact, since composition attributes are applied to the group, it is a perfect replacement. There is no layer element in SVG as nothing would be gained by having one. Nested groups (or CSS classes) can handle the case where multiple elements are grouped for layering but need to inherit different presentation attributes.

Altering Layering Using JavaScript

Any element can be reordered by using JavaScript to move them around the DOM. First, the element to be moved is found. It is then removed and added in its new location.

Example 1. Click parts of monkey to send to the back. (Download)
1
2
3
4
5
6
function moveToBack(layerToMove) {
  var monkeyHolder = document.getElementById("monkeyLayers");
  
  monkeyHolder.removeChild(layerToMove);
  monkeyHolder.insertBefore(layerToMove, monkeyHolder.firstChild);
}
Code 2. Moves the group to the back.

The above example shows how the SVG DOM can be altered using JavaScript to layer shapes.

Related Topics