Fabric JS:当线在一组中移动时计算线坐标

Fabric JS: Calculating line coordinates when the line moves in a group

在这个 jsFiddle 中,我有一个 Fabric 线和一个 rect。我的objective是在自己移动或者和rect成组移动的时候获取线坐标

如果你只 select 直线并移动它,坐标会正确显示(我从 here 中获取了函数)。

但是如果你select 直线和矩形,这个函数就不起作用了。我用e.target._objects[0]来获取线路,好像没问题。

如何获取组内移动的线坐标?

组内的对象相对于组定位,并且它们的坐标相对于组的中心重新计算。当它在组中移动时,应考虑这些因素。

让我们做一个仅左上角坐标的简化示例。该行的绝对左上角坐标由以下公式给出:

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

请检查这个简化的 CodeSandbox 示例:https://codesandbox.io/s/Whosebug-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];
  }
}