javascripthtmlsvgdomsnap.svg

Combining two snap svg groups into one single group


I have two snap svg groups grp1 and grp2. Now I want to combine these two groups to become one group. I have tried append(), appendTo(), prepend(), prependTo() but all of them add one group inside another in one way or the other.

Here is code on JSFiddle

Does anybody have any idea how to achieve this?


Solution

  • Using SnapSVG, you are not working with Nodes

    That means your g1 and g2 are Snap Objects

    To use DOM methods like append, you need to dig a little deeper to access the Nodes

    The advantage of SnapSVG is you can chain methods

    Working code:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.5.1/snap.svg-min.js"></script>
    
    <svg id="Canvas" height="100"></svg>
    
    
    <script>
    let canvas = Snap('#Canvas');
    
    let g1 = canvas.g()
                   .add(canvas.rect(10, 10, 80, 60).attr({fill: 'green'}))
                   .add(canvas.circle(150, 60, 40 ).attr({fill: 'gold'}));
    let g2 = canvas.g()
                   .add(canvas.circle(150, 60, 20 ).attr({fill: 'red'}));
    
    g1.node.append(...g2.node.children);
    g2.remove();
    
    document.body.append(canvas.node.innerHTML)
    </script>