Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning an svg group

Tags:

clone

svg

I have an svg group which contains some elements, I want to clone the group, problem is the function clones only one element of the group. Here is the function

 <script type="text/ecmascript"><![CDATA[
    function clone(evt) {
        var cloneElement = evt.target.cloneNode(false);
        var newx = 100;
        var newy = 500;
        cloneElement.setAttributeNS(null,"x",newx);
        cloneElement.setAttributeNS(null,"y",newy);
        document.getElementById("layer1").appendChild(cloneElement);
    }

]]></script>

The svg looks something like

<g id="layer1" onclick="clone(evt)">
<rect>
<path>
<circle>
<circle>
</g>

The rectangle is like a container and what happens is that the function clones the rectangle and leaves the other elements. So what is wrong?

like image 437
user979830 Avatar asked Sep 15 '25 01:09

user979830


1 Answers

Two things:

  • cloneNode should be passed true if you want a deeply cloned tree, otherwise it will just clone one element
  • evt.target will always be the element where the event originated, and g elements are never hit directly, the mouse events just bubble up to there from the children. You can use evt.currentTarget instead if you want the element which is currently handling the event (in your case that would be the g element).
like image 155
Erik Dahlström Avatar answered Sep 16 '25 21:09

Erik Dahlström