你能帮我理解如何在 fabric.js 中获取对象的实际坐标,而不是它的边界矩形吗?
getBoundingRect
在那里获取边界框坐标。但是我没有找到任何方法或自定义方法来找到实际的形状坐标,如下图所示。
我正在使用fabric 5.
const fc = new fabric.Canvas("c");
fc.on('selection:created', event => {
console.log("Bounding Rect: ", event.target.item(0).getBoundingRect());
console.log("How to find actual coord?? ");
});
const triangle1Options = {
stroke: 'black',
strokeWidth: 2,
fill: 'red',
left: 10,
top: 10,
width: 100,
height: 100,
}
let triangle1 = new fabric.Triangle(triangle1Options);
const group1 = new fabric.Group([triangle1], {
selectable: true,
lockScalingFlip: true,
lockUniScaling: true,
subTargetCheck: true,
lockScalingX: false,
lockScalingY: false,
objectCaching: false,
noScaleCache: true
});
group1.add(triangle1);
fc.add(group1);
// Create the first parallelogram
var parallelogram1 = new fabric.Path('M 0 0 L 100 0 L 150 50 L 50 50 z', {
left: 150,
top: 50,
stroke: 'black',
strokeWidth: 2,
fill: 'red',
});
const group2 = new fabric.Group([parallelogram1], {
selectable: true,
lockScalingFlip: true,
lockUniScaling: true,
subTargetCheck: true,
lockScalingX: false,
lockScalingY: false,
objectCaching: false,
noScaleCache: true
});
// Add the shapes and line to the canvas
fc.add(group2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.1.0/fabric.min.js"></script>
<canvas id="c" width="400" height="300" />
非常感谢任何帮助。我愿意接受新的想法来实现我的目标,如下所述。
目标 是在每个顶点中间创建一个额外的形状(一个带有文本的矩形)。但为此我需要形状的实际坐标。
要找出顶点坐标,使用
fabric.Polygon
而不是 fabric.Rect
或 fabric.Triangle
更容易。使用多边形,我们可以直接访问形成它的点,而且我们可以用它们创建三角形和矩形。
基本上你需要多边形的点并将它们从对象平面转换到画布平面,这样你就可以获得相对于画布的坐标。
下面的函数就是这样做的。它以
fabric.Polygon
作为参数并返回画布平面中的顶点。
function getPolyVertices(poly) {
const points = poly.points,
vertices = [];
points.forEach((point) => {
const x = point.x - poly.pathOffset.x,
y = point.y - poly.pathOffset.y;
vertices.push(
fabric.util.transformPoint(
{ x: x, y: y },
fabric.util.multiplyTransformMatrices(
poly.canvas.viewportTransform,
poly.calcTransformMatrix()
)
)
);
});
return vertices;
}
如果您想更好地了解此功能的工作原理并查看其工作示例(如下图),我建议阅读此处的这篇文章。 披露:我是这篇文章的作者。