Search code examples
kineticjs

kineticjs how do I remove an object from a group


How can I remove a specific object from a group. I would like the object to stay on the layer, but outside of the group. Thanks


Solution

  • You can use myElement.moveTo(myLayer) to ungroup myElement and place it onto myLayer as an independent element.

    The only small gotcha in this ungrouping is that myElement's [x,y] was relative to the group. When you remove myElement from the group, you must adjust myElement's [x,y] by the group's [x,y]. That code would look like this:

    // move myElement out of myGroup an onto myLayer
    myElement.moveTo(myLayer);
    
    // adjust myElement's [x,y] by myGroup's [x,y]
    myElement.x(myElement.x()+myGroup.x());
    myElement.y(myElement.y()+myGroup.y());
    
    // redraw myLayer
    myLayer.draw();
    

    Example code and a Demo:

        var stage = new Kinetic.Stage({
            container: 'container',
            width: 350,
            height: 350
        });
        var layer = new Kinetic.Layer();
        stage.add(layer);
    
    
        var g=new Kinetic.Group({draggable:true});
        var r=new Kinetic.Rect({x:10,y:10,width:50,height:50,fill:'blue'});
        var c=new Kinetic.Circle({x:50,y:50,radius:15,fill:"red"});
        g.add(r);
        g.add(c);
        layer.add(g);
        layer.draw();
    
        $('#ungroup').click(function(){
            c.moveTo(layer);
            c.x(c.x()+g.x());
            c.y(c.y()+g.y());
            layer.draw();
        });
    body{padding:20px;}
    #container{
      border:solid 1px #ccc;
      margin-top: 10px;
      width:350px;
      height:350px;
    }
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.1.0.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    
    <button id=ungroup>Move red circle out of group into layer</button>
    
    <h4>BlueRect and RedCircle are in a draggable group.<br>Test:<br>Drag the group,<br>Click the 'Move red circle...' button,<br>Drag the group again<br>RedCircle is un-grouped</h4>
    
    <div id="container"></div>