Skip to main content

Shape Layering

To layer shapes with Konva, we can use one of the following layering methods: moveToTop(), moveToBottom(), moveUp(), moveDown(), or zIndex(). You can also layer groups and layers.

Instructions: Drag and drop the boxes to move them around, and then use the buttons on the left to reorder the yellow box.

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();
layer.draw();
});

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

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


</rewritten_file>