Reputation: 9
i have two objects (2 shape objects/ 1 shape object and 1 text object) which are at the same alignment on the canvas. i wish to know is there any way to find out which object is on the top from them.
canvas.getObjects(); this will give me the list of all the objects that are on canvas but i want which one is on the top?
Upvotes: 1
Views: 451
Reputation: 4988
FabricJS doesn't have an explicit z-index property, akin to CSS z-index
. The way things are rendered is: get an array of visible objects and draw them one by one, starting from the first one. The first object ends up underneath all others, while the last one ends up on top.
However, you should keep in mind that with canvas.preserveObjectStacking
set to false
(also false
by default), active objects are always rendered on top, no matter their position in the array.
If you don't care about the active objects, you can simply compare the objects' indices:
const canvas = new fabric.Canvas('c')
const rectR = new fabric.Rect({
width: 100,
height: 100,
fill: 'red'
})
const rectG = new fabric.Rect({
left: 50,
top: 50,
width: 100,
height: 100,
fill: 'green'
})
canvas.add(rectR, rectG)
console.log('red rect index:', canvas.getObjects().indexOf(rectR))
console.log('green rect index:', canvas.getObjects().indexOf(rectG))
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.5/fabric.js"></script>
<canvas id="c" width="500" height="400"></canvas>
Upvotes: 2