Search code examples
javascriptfabricjs

how go get items from a group in fabric.js


I am using v5 of fabric.js

I can see from the docs how to make groups but no guidance on when this is done via the UI. In my case, the user will use their mouse to create a group (holding shift/cmd) and clicking on canvas elements, which creates an outer box/group, and then all items can be moved/scaled proportionally

eg

enter image description here

This is what I've tried

const canvas = new fabric.Canvas("myId"); 

canvas.on("object:modified", hasBeenModified);

function hasBeenModified(evt) {
    var az = evt.target.canvas.targets; //empty array. I thought it should show all the items that are in the group
}

If I use evt.target._objects I can see all my items but, the left positions are of a negative value, which can't be right (as I moved the objects to the right so the value should increase in number)

This approach works great when a single object is moved and I can use the following syntax.

console.log("original width: " + evt.target.get('width'));

GitHub issues suggests using targets, but it's always an empty array

However, I'm expecting to get an array out of fabric.js so I can iterate over each item that moved and get the latest properties, and find it's location within the canvas element (not within the group)

After a user groups multiple items within the canvas (by using their keyboard/mouse), modifies them (scales/drags), how do I find the new size/location (or any other property) of each item


Solution

  • In the end I called the toJSON (which is also called via JSON.stringify) - this provides an array of objects which has all of the detail I needed

    const c = new fabric.Canvas("c")
    console.log(JSON.stringify(c));
    

    However, the real answer is

    c.getActiveObjects()