Moving SVG elements in Z


July 3, 2011 Code on Github

Introduction

This a quick post which isn't directly about making SVGs interactive, but could be useful for an interactive SVG. It was prompted by a question of Stack Overflow about how to move one element drawn after another below it.

Because of the way SVG works, sequentially drawing elements on the page in the order they are in the file, there is no simple way to do this. Instead you have to play with the DOM, grabbing the element you want to bury and inserting it into the beginning of the document.

The code

In the following SVG, a group of two lines is drawn after two circles, but moved in front of them with a short bit of Javascript.

<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
    <circle cx="80" cy="80" r="40" fill="blue"/>
    <circle cx="120" cy="120" r="40" fill="green"/>

    <g id="line-group" stroke-width="2" stroke="black">
        <line x1="0" y1="10" x2="190" y2="200" />
        <line x1="10" y1="0" x2="200" y2="190" />
    </g>

    <script type="text/javascript"><![CDATA[
        var svg = document.getElementsByTagName("svg")[0];
        var line_group = document.getElementById("line-group");
        svg.insertBefore(line_group, svg.firstChild);
    ]]></script>
</svg>

Despite the line group being after the after the circles, the lines should be drawn below the circles. In somes cases, such as the thumbnail generated by my computer, or if you open the SVG in Inkscape, the script isn't called and the lines are drawn on top of the circles.

All the work is done in lines 12 and 13. Line 12 grabs the group of lines, line 13 inserts it into the svg before all the other elements.

Leave a comment

cancel reply