Search code examples
kineticjsdrag

KineticJS sharing one object between two groups


I am using KineticJS to draw a vertical line and a horizontal line and a circle in the middle. I have grouped the vertical line and circle, however I would like to move the circle with the horizontal line as well, here is my script:

var stage1 = new Kinetic.Stage({
                container: 'container',
                width: 1024,
                height: 1024
            });
              var blayer1 = new Kinetic.Layer();
            var bgroup1 = new Kinetic.Group({
                draggable: true,
                dragBoundFunc: function (pos) {
                    return {
                        x: pos.x,
                        y: this.getAbsolutePosition().y
                    }
                }
            });
            var BlueLine1 = new Kinetic.Line({
                points: [512, 0, 512, 1024],
                stroke: '#0080c0',
                strokeWidth: 2,
                lineCap: 'round',
                lineJoin: 'round'
            });
            var circle = new Kinetic.Circle({
                x: stage1.getWidth() / 2,
                y: stage1.getHeight() / 2,
                radius: 140,
                stroke: '#00ffff',
                strokeWidth: 2
            });
            bgroup1.add(circle);
            bgroup1.add(BlueLine1);
            blayer1.add(bgroup1);
            stage1.add(blayer1);
            blayer1.draw();

            var glayer1 = new Kinetic.Layer();
            var ggroup1 = new Kinetic.Group({
                draggable: true,
                dragBoundFunc: function (pos) {
                    return {
                        x: this.getAbsolutePosition().x,
                        y: pos.y
                    }
                }
            });
            var GreenLine1 = new Kinetic.Line({
                points: [0, 512, 1024, 512],
                stroke: 'red',
                strokeWidth: 2,
                lineCap: 'round',
                lineJoin: 'round'
            });
            ggroup1.add(GreenLine1);
            glayer1.add(ggroup1);
            stage1.add(glayer1);
            glayer1.draw();
        }

Solution

  • Here's how to share your one circle between your 2 groups

    Use ".moveTo()" to move the circle into whichever group you need.

    This moves your circle into ggroup1, so ggroup1 now has your vertical line and your circle:

    circle.moveTo(ggroup1);
    blayer1.draw();
    glayer1.draw();
    

    This moves your circle into the bgroup1, so bgroup1 now has your horizontal line and your circle:

    circle.moveTo(bgroup1);
    blayer1.draw();
    glayer1.draw();
    

    BTW, I see you're using 2 separate layers. I assume the purpose of the 2 layers is for something else you are doing. But, you don't need 2 layers to make circle-sharing possible. You can have 2 groups on 1 layer and still just move the circle between the 2 groups.