In this jsFiddle I have one Fabric line and one rect. My objective is to get the line coordinates when it moves by itself or in a group with the rect.
If you only select the line and move it, the coordinates are displayed correctly (I took the function from here).
But if you select both the line and the rect, the function does not work. I use e.target._objects[0]
to get the line, that seems to be fine.
How to get the line coordinates when it's moved in the group?
The objects inside the group are positioned in relation to the group and their coordinations are recalculated in relation to the center of the group. When it is moved in the group these factors should be considered.
Let's make a simplified example of only the top left coordinate. The absolute top left coordinate of the line is given by this formula:
'Absolute Line TL X' = 'Group top X left value' + (('Group width' / 2) + 'Line top left X value')
'Absolute Line TL Y' = 'Group top Y left value' + (('Group height' / 2) + 'Line top left Y value')
Please check this simplified CodeSandbox example: https://codesandbox.io/s/stackoverflow-60416193-fabric-js-362-qpofr
canvas.on("object:moving", function(e) {
var target;
var coords;
if (e.target._objects) {
target = e.target._objects[0];
coords = calcLineCoords(target, e.target);
} else {
target = e.target;
coords = calcLineCoords(target);
}
caption.text = coords + "";
});
function calcLineCoords(line, groupContainer) {
const { tl } = line.calcCoords();
let coordsStart = tl;
if (!!groupContainer) {
const groupCoordinates = groupContainer.calcCoords();
let groupCoordsStart = groupCoordinates.tl;
var lineTopLeftX =
groupCoordsStart.x + (groupContainer.get("width") / 2 + coordsStart.x);
var lineTopLeftY =
groupCoordsStart.y + (groupContainer.get("height") / 2 + coordsStart.y);
return [lineTopLeftX, lineTopLeftY];
} else {
return [coordsStart.x, coordsStart.y];
}
}