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

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