如何在Fabric.js中为两个不对称图形创建连接线?
解决方案:Fabric.js 5 中获取图形顶点实现精准连线
需求
用线条连接两个三角形(或其他图形),使线条精准连接图形顶点,预期效果如下:
当前问题
使用getBoundingRect()仅能获取图形的包围盒坐标,导致连线从图形的MR/ML控制点出发,无法触及实际顶点,效果如下:
以下是几种实现精准连线的方案:
方案1:通过getPoints()获取顶点并转换为画布坐标
Fabric.js内置图形(如Triangle)提供getPoints()方法,返回图形自身坐标系下的顶点,通过toCanvasPoint()可转换为画布绝对坐标:
const fc = new fabric.Canvas("c"); const triangle1Options = { stroke: 'black', strokeWidth: 2, fill: 'red', left: 10, top: 10, width: 100, height: 100, } let triangle1 = new fabric.Triangle(triangle1Options); fc.add(triangle1); fc.on('selection:created', event => { const shape = event.target; // 获取图形自身坐标系的顶点 const localVertices = shape.getPoints(); // 转换为画布全局坐标系的坐标 const canvasVertices = localVertices.map(point => shape.toCanvasPoint(point)); console.log('画布坐标系顶点:', canvasVertices); });
方案2:针对特定图形直接计算顶点
以三角形为例,可通过图形的left、top、width、height属性直接计算顶点(未旋转场景):
- 顶部顶点:
{ x: shape.left + shape.width/2, y: shape.top } - 左下角顶点:
{ x: shape.left, y: shape.top + shape.height } - 右下角顶点:
{ x: shape.left + shape.width, y: shape.top + shape.height }
方案3:处理旋转后的图形顶点
若图形存在旋转,需结合旋转角度计算顶点,先获取图形中心,再通过三角函数转换偏移量:
// 计算旋转后三角形的画布坐标顶点 function getRotatedTriangleVertices(triangle) { const center = triangle.getCenterPoint(); const halfWidth = triangle.width / 2; const height = triangle.height; const angleRad = fabric.util.degreesToRadians(triangle.angle); // 自身坐标系下顶点相对于中心的偏移量 const localOffsets = [ { x: 0, y: -height/2 }, // 顶部顶点 { x: -halfWidth, y: height/2 }, // 左下角顶点 { x: halfWidth, y: height/2 } // 右下角顶点 ]; // 应用旋转并转换为画布全局坐标 return localOffsets.map(offset => { const rotatedX = offset.x * Math.cos(angleRad) - offset.y * Math.sin(angleRad); const rotatedY = offset.x * Math.sin(angleRad) + offset.y * Math.cos(angleRad); return { x: center.x + rotatedX, y: center.y + rotatedY }; }); } // 使用示例 fc.on('selection:created', event => { const vertices = getRotatedTriangleVertices(event.target); console.log('旋转后的顶点坐标:', vertices); });
内容的提问来源于stack exchange,提问作者Chhavi Kohli
相关产品推荐
相关产品推荐

