I am working on a project in which I have to add rectangles and add triangles into those rectangles. I get the currently selected rectangle using this
const rect = canvas.getActiveObject().aCoords
Then I check if the mouse click is in the rectangle and if true I add a triangle.
const x = event.pointer.x
const y = event.pointer.y
if (rect.tl.x + 20 < x < rect.br.x - 20 && rect.tl.y + 20 < y < rect.br.y - 20) {
var points = regularPolygonPoints(3, 10);
var myPoly = new fabric.Polygon(points, {
stroke: 'red',
left: x,
top: y,
strokeWidth: 2,
strokeLineJoin: 'bevil'
}, false);
canvas.add(myPoly);
}
The problem is the whenever the rectangle is selected it comes on top of all the added triangles and only after I click away to deselect the rectangle, the triangles appear from beneath.
Please see the images below to better understand
Unselected
Selected rectangle coming on top of the triangles
What I want is that even if the rectangle is selected it always stays below the triangles.
http://fabricjs.com/docs/fabric.Canvas.html#preserveObjectStacking
Indicates whether objects should remain in current stack position when selected. When false objects are brought to top and rendered as part of the selection group
Set your canvas.preserveObjectStacking to true (it's false by default).
It will prevent the selection from bringing objects to the front, but keep in mind that this will rely on the order in which you've added your objects.