Skip to main content

形状层级

要在 Konva 中调整形状层级,我们可以使用以下层级方法之一: moveToTop()moveToBottom()moveUp()moveDown()zIndex()。 您也可以对组和图层进行分层。

说明:拖放盒子以移动它们,然后使用左侧的按钮重新排列黄色盒子。

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

const yellowBox = new Konva.Rect({
x: 50,
y: 50,
width: 100,
height: 100,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
draggable: true,
});

const redBox = new Konva.Rect({
x: 100,
y: 100,
width: 100,
height: 100,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
draggable: true,
});

layer.add(yellowBox);
layer.add(redBox);
stage.add(layer);

// 创建按钮
const toTopBtn = document.createElement('button');
toTopBtn.textContent = '将黄色方块移至顶层';
toTopBtn.addEventListener('click', () => {
yellowBox.moveToTop();
});

const toBottomBtn = document.createElement('button');
toBottomBtn.textContent = '将黄色方块移至底层';
toBottomBtn.addEventListener('click', () => {
yellowBox.moveToBottom();
});

document.body.prepend(toTopBtn);
document.body.prepend(toBottomBtn);