如何获取GoJS中Shape或Geometry的边缘坐标与最大最小XY值?
解决GoJS中获取自定义形状实际边界并填充小方块的问题
核心问题原因
你使用的shape.naturalBounds是Shape所在Panel的局部坐标系边界,对于Auto布局的Node来说,Shape的局部坐标原点默认是节点内部的(0,0),和节点在图中的实际位置无关,所以无法得到形状在画布中的真实范围。
解决方案:使用文档坐标系边界
GoJS提供了shape.getDocumentBounds()方法,它会返回Shape在**文档坐标系(即画布全局坐标系)**中的实际边界矩形,包含了节点位置、旋转等所有变换后的真实位置,完全符合你的需求。
同时需要注意:geometry.containsPoint()接收的是Shape局部坐标系下的点,所以判断时需要先把文档坐标转换为Shape局部坐标,用shape.getLocalPoint(goPoint)方法完成转换。
修改后的代码示例
填充小方块的逻辑代码
//handle seating population if (confirm("Populate this shape with chairs?") == true){ // 获取形状在画布中的真实边界 const docBounds = shape.getDocumentBounds(); const minX = docBounds.x; const maxX = docBounds.x + docBounds.width; const minY = docBounds.y; const maxY = docBounds.y + docBounds.height; const chairSize = 20; // 自定义小方块的尺寸 // 遍历边界范围内的所有可能小方块位置 for (let x = minX; x <= maxX - chairSize; x += chairSize) { for (let y = minY; y <= maxY - chairSize; y += chairSize) { // 小方块四个角的文档坐标 const topLeft = new go.Point(x, y); const topRight = new go.Point(x + chairSize, y); const bottomLeft = new go.Point(x, y + chairSize); const bottomRight = new go.Point(x + chairSize, y + chairSize); // 转换为Shape局部坐标系下的点 const localTL = shape.getLocalPoint(topLeft); const localTR = shape.getLocalPoint(topRight); const localBL = shape.getLocalPoint(bottomLeft); const localBR = shape.getLocalPoint(bottomRight); // 判断四个角是否都在形状内部 if (shape.geometry.containsPoint(localTL) && shape.geometry.containsPoint(localTR) && shape.geometry.containsPoint(localBL) && shape.geometry.containsPoint(localBR)) { // 计算小方块节点的中心坐标(因为你的addNode用location设置节点中心) const chairCenterX = x + chairSize / 2; const chairCenterY = y + chairSize / 2; addNode("Rectangle", "lightblue", "", chairCenterX, chairCenterY, chairSize); } } } }
补充说明
- 边界范围计算:遍历终点减去小方块尺寸,避免生成超出形状边界的小方块。
- 坐标转换:必须通过
getLocalPoint转换坐标,否则containsPoint的判断会基于局部坐标系,结果完全错误。 - 旋转兼容:如果你的自定义形状有旋转,
getDocumentBounds和getLocalPoint会自动处理旋转变换,判断逻辑依然有效。
内容的提问来源于stack exchange,提问作者Knight0Light
相关产品推荐
相关产品推荐

