How to set correct order of nodes using zIndex?

What is zIndex of a node?

You can get/set zIndex of a node in this way:

// get
const zIndex = shape.zIndex();

// set

zIndex is just index of a node in its parent children array. Please don’t confuse zIndex in Konva with z-index in CSS.

const group = new Konva.Group();

const circle = new Konva.Circle({});


// it will log 0.

// the next line will not work. Because the group have only one child

// still logs 0

// for any node that equations will be true:
console.log(circle.zIndex() === circle.getParent().children.indexOf(circle))

You can’t use zIndex to set absolute position of the node, like we do this in CSS.
Konva is drawing nodes in the strict order as they defined in nodes tree.

Let make a demo. I will create a layer with two groups. The first group has two shapes (black rect and red circle). The second group has one shape (green rect).

Show source code!

Konva ZIndex demoview raw
<!DOCTYPE html>
<script src="[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Shape Layering Demo</title>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
<div id="container"></div>
var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
container: 'container',
width: width,
height: height,

var layer = new Konva.Layer();

// create first group with two shapes
var group1 = new Konva.Group();

var blackRect = new Konva.Rect({
x: 20,
y: 20,
fill: 'black',
width: 100,
height: 100,

var redCircle = new Konva.Circle({
x: 70,
y: 70,
fill: 'red',
radius: 30,

// now the red circle on on top of black rectangle
// we can change its zIndex with:

// if we what to move it back to the top we can change its zIndex again
// or we can change zIndex of black rectangle:
// after that zIndex of red circle will be changed back to 1:
console.log('red circle index: ' + redCircle.zIndex());

// crete second group with one shape
var group2 = new Konva.Group();

var greenRect = new Konva.Rect({
x: 70,
y: 70,
width: 100,
height: 100,
fill: 'green',

What is zIndex of red circle. It is 1 (second element in array of children of the first group).
What is zIndex of green rect? It is 0.

Red circle has higher zIndex than green rect. But why we see green rect above red circle? As mentioned above Konva is drawing in strict order of the tree.
So at first it will draw all children of the first group. Then above that picture it will draw all children of the second group (and so on if we have more elements in the layer).

How to draw red circle above green rect? You can move it into the second group. Or you can move it into the layer and make sure it has larger zIndex than previous groups.

Enjoying Konva? Please consider to support the project.