Skip to main content

Move Shape to Another Container

To move a shape from one container into another with Konva, we can use the moveTo() method which requires a container as a parameter. A container can be another stage, a layer, or a group. You can also move groups into other groups and layers, or shapes from groups directly into other layers.

Instructions: Drag and drop the groups and observe that the red rectangle is bound to either the yellow group or the blue group. Use the buttons on the left to move the box from one group into another.

import Konva from 'konva';

const width = window.innerWidth;
const height = window.innerHeight;

const stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});

const layer = new Konva.Layer();

// yellow group

const group1 = new Konva.Group({
x: 50,
y: 50,
draggable: true,
});

const yellow = new Konva.Rect({
width: 100,
height: 100,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
});
group1.add(yellow);

// blue group

const group2 = new Konva.Group({
x: 200,
y: 50,
draggable: true,
});

const blue = new Konva.Rect({
width: 100,
height: 100,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
group2.add(blue);

// red box

const redBox = new Konva.Rect({
x: 10,
y: 10,
width: 30,
height: 30,
fill: 'red',
});
group1.add(redBox);

layer.add(group1);
layer.add(group2);
stage.add(layer);

// create buttons

const moveToGroup1Btn = document.createElement('button');
moveToGroup1Btn.textContent = 'Move to yellow group';
moveToGroup1Btn.addEventListener('click', () => {
redBox.moveTo(group1);
layer.draw();
});

const moveToGroup2Btn = document.createElement('button');
moveToGroup2Btn.textContent = 'Move to blue group';
moveToGroup2Btn.addEventListener('click', () => {
redBox.moveTo(group2);
layer.draw();
});

document.body.appendChild(moveToGroup1Btn);
document.body.appendChild(moveToGroup2Btn);