You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

画布拖拽场景下三个矩形间参考线的坐标与尺寸计算

形状对齐参考线坐标与尺寸计算方案

我正在开发一款类似Figma的可拖拽形状画布,需要在形状对齐时绘制X、Y方向的参考线。目前已处理完形状对齐的触发逻辑,也能获取到对齐时的矩形参数,但不清楚参考线的坐标与尺寸计算方法。以下是示例矩形参数和需要设置的参考线样式,需计算出对应的属性值。

示例矩形参数

"firstRect": { 
  "x": 827, "y": 282, "width": 95, "height": 43, 
  "right": 923, "bottom": 325, "top": 282, "left": 827
},
"secondRect": { 
  "x": 745, "y": 365, "width": 82, "height": 42, 
  "right": 827, "bottom": 407, "top": 365, "left": 745
},
"currentRect": { 
  "x": 938, "y": 369, "width": 134, "height": 80, 
  "top": 369, "right": 1073, "bottom": 449, "left": 938
}

需设置的参考线样式

guideLineX.style.left = `.. px`
guideLineX.style.top = `..px`
guideLineX.style.width = '1px'
guideLineX.style.height = `..px`

guideLineY.style.left = `..px`
guideLineY.style.top = `..px`
guideLineY.style.width = `...px`
guideLineY.style.height = '1px'

参考线计算逻辑与示例数值

垂直参考线(guideLineX,竖线)

垂直参考线用于标记X轴方向的对齐(左边缘、右边缘、中心对齐),计算规则:

  • left:取对齐的X坐标(左边缘对齐取矩形left值,右边缘对齐取right值,中心对齐取(left + right)/2)
  • top:取所有参与对齐的矩形中最小的top值,确保参考线覆盖对齐形状的垂直范围
  • height:所有参与对齐的矩形中最大的bottom值 减去 最小的top值

示例:firstRect与secondRect的边缘对齐

对齐X坐标为827px(firstRect.left = secondRect.right),参与对齐的两个矩形最小top是282,最大bottom是407:

guideLineX.style.left = `827px`
guideLineX.style.top = `282px`
guideLineX.style.height = `125px` // 407 - 282 = 125

水平参考线(guideLineY,横线)

水平参考线用于标记Y轴方向的对齐(上边缘、下边缘、中心对齐),计算规则:

  • top:取对齐的Y坐标(上边缘对齐取矩形top值,下边缘对齐取bottom值,中心对齐取(top + bottom)/2)
  • left:取所有参与对齐的矩形中最小的left值,确保参考线覆盖对齐形状的水平范围
  • width:所有参与对齐的矩形中最大的right值 减去 最小的left值

示例:currentRect与secondRect的上边缘对齐

对齐Y坐标为365px(secondRect.top),参与对齐的两个矩形最小left是745,最大right是1073:

guideLineY.style.top = `365px`
guideLineY.style.left = `745px`
guideLineY.style.width = `328px` // 1073 - 745 = 328

内容的提问来源于stack exchange,提问作者Mert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:50:37