MyDaftQuestions
MyDaftQuestions

Reputation: 4701

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

Upvotes: 2

Views: 162

Answers (2)

MyDaftQuestions
MyDaftQuestions

Reputation: 4701

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()

Upvotes: 0

Heiko Theißen
Heiko Theißen

Reputation: 16892

I played around a bit with http://fabricjs.com/events and developed the following theory:

The object:modified event of a group contains the following properties:

"target": {
  "type": "activeSelection",
  "left": x,
  "top": y,
  "width": dx,
  "height": dy, ...,
  "objects": [
    {
      "type": "...",
      "left": x1,
      "top": y1,
      "width": dx1,
      "height": dy1, ...,
    },
    {
      "type": "...",
      "left": x2,
      "top": y2,
      "width": dx2,
      "height": dy2, ...,
    }, ...
  ]
}

The left and top of the embedded objects are relative to the midpoint of the active selection. In other words:

After the move/scale, the leftmost point of the first object is x + dx/2 + x1 and its topmost point is y + dy/2 + y1. Similarly for the other objects.

Upvotes: 1

Related Questions