Fabric JS:当线在组中移动时计算线坐标 [英] Fabric JS: Calculating line coordinates when the line moves in a group
问题描述
在此 jsFiddle 中,我有一个Fabric行和一个rect.我的目标是在直线移动或与矩形成组移动时获得线坐标.
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).
但是,如果同时选择了行和矩形,则该功能将不起作用.我使用 e.target._objects [0]
来获取行,这似乎很好.
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')
请检查以下简化的CodeSandbox示例: https://codesandbox.io/s/stackoverflow-60416193-fabric-js-362-qpofr
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];
}
}
这篇关于Fabric JS:当线在组中移动时计算线坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!