Moving SVG elements in Z

This a quick post 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.

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 EMCAScript.

<svg width="200" height="200" version="1.1"
  xmlns="http://www.w3.org/2000/svg"
  onload="init(evt)">

<script type="text/emcascript">
<![CDATA[
  function init(evt) {
    if ( window.svgDocument == null ) {
      svgDoc = evt.target.ownerDocument;
    }

    var line_group = svgDoc.getElementById("line-group")
    svgDoc.documentElement.insertBefore(line_group, svgDoc.documentElement.firstChild);
  }
]]>
</script>

<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>

</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 svgDoc.documentElement before all the other elements.

AttachmentSize
underlines.svg898 bytes

Comments

The world calls it "javascript", but if you're going to be pedantic, shouldn't you call it "ecmascript", not "emcascript" :)

That aside, it's a very handy article!

Post new comment

The content of this field is kept private and will not be shown publicly.