Preventing Fabric.js Objects from Changing Z-Index During Selection

When managing multiple layers within a Fabric.js canvas, the default interaction model immediately brings the active element to the foreground. This means that if a lower-layer object is selected, it visually jumps above overlapping elements until it is deselected, at which point it returns to its original stacking order. While this helps in identifying the selected item, it can be disorienting when working with strict graphical hierarchies.

Default Stacking Behavior

By default, Fabric.js manages the render order dynamically during interaction. Consider the following implementation where two shapes overlap:

<canvas id="workspace" width="500" height="400" style="border: 1px solid #333;"></canvas>

<!-- Import Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"></script>

<script>
  const editor = new fabric.Canvas('workspace');
  
  // Define the base layer element
  const primaryShape = new fabric.Circle({
    radius: 40,
    fill: '#3498db',
    top: 60,
    left: 60
  });

  // Define the top layer element
  const secondaryShape = new fabric.Rect({
    width: 90,
    height: 90,
    fill: '#e74c3c',
    top: 90,
    left: 90
  });

  // Add to canvas (Circle is added first, Rect is on top)
  editor.add(primaryShape, secondaryShape);
</script>

In the scenario above, the rectangle visually covers the circle. However, upon selecting the circle, the library temporarily alters the stacking context, pushing the circle to the top. Releasing the selection restores the original z-index.

Maintaining Static Z-Index

To disable the automatic reordering and ensure objects stay in their assigned layer regardless of selection state, the preserveObjectStacking configuration option must be enabled during initialization. This ensures that selection handles appear without modifying the render order.

const editor = new fabric.Canvas('workspace', {
  preserveObjectStacking: true
});

Setting this property to true allows users to interact with lower-layer objects without them visually obscuring upper-layer objects, providing a more predictable editing experience.

Tags: fabricjs javascript html5-canvas frontend-development ui-interaction

Posted on Wed, 01 Jul 2026 17:27:36 +0000 by Jay