跳到主要内容

图形层叠

要使用 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);

// create buttons
const toTopBtn = document.createElement('button');
toTopBtn.textContent = 'Move yellow box to top';
toTopBtn.addEventListener('click', () => {
yellowBox.moveToTop();
});

const toBottomBtn = document.createElement('button');
toBottomBtn.textContent = 'Move yellow box to bottom';
toBottomBtn.addEventListener('click', () => {
yellowBox.moveToBottom();
});

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