跳到主要内容

将图形移动到其他容器

要使用 Konva 将图形从一个容器移动到另一个容器,可以使用 moveTo() 方法。此方法需要一个容器作为参数。 容器可以是另一个舞台、图层或组。你也可以将组移动到其他组或图层中,或将组中的图形直接移动到其他图层中。

操作说明:拖放这些组,观察红色矩形绑定到黄色组还是蓝色组。使用左侧按钮将矩形从一个组移动到另一个组。

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);
});

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

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