Monday 25 October 2021

Fabric.js Canvas - Make one type of object always stay below the other

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

enter image description here

Selected rectangle coming on top of the triangles

enter image description here

What I want is that even if the rectangle is selected it always stays below the triangles. Any help will be appreciated. Thank You.



from Fabric.js Canvas - Make one type of object always stay below the other

No comments:

Post a Comment