如何基于角度动态使用GoJS绘制圆锥图形?
如何基于角度动态绘制圆锥?

我已有一段用于绘制简单贝塞尔曲线的代码如下:
var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3); go.Shape.defineFigureGenerator("Cone3", function(shape, w, h) { var geo = new go.Geometry(); var cpxOffset = KAPPA * .5; var cpyOffset = KAPPA * .1; var fig = new go.PathFigure(0, .9 * h, true); geo.add(fig); fig.add(new go.PathSegment(go.PathSegment.Line, .5 * w, 0)); fig.add(new go.PathSegment(go.PathSegment.Line, w, .9 * h)); fig.add(new go.PathSegment(go.PathSegment.Bezier, .5 * w, h, w, (.9 + cpyOffset) * h, (.5 + cpxOffset) * w, h)); fig.add(new go.PathSegment(go.PathSegment.Bezier, 0, .9 * h, (.5 - cpxOffset) * w, h, 0, (.9 + cpyOffset) * h).close()); geo.spot1 = new go.Spot(.25, .5); geo.spot2 = new go.Spot(.180, .97); return geo; });
实现动态角度的圆锥绘制
要基于角度动态调整圆锥形状,可通过给Shape添加自定义属性传递角度参数,在图形生成器中计算对应顶点与底边位置:
- 修改图形生成器,支持角度参数
利用三角函数根据顶点夹角计算圆锥底边宽度,动态调整路径:
var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3); go.Shape.defineFigureGenerator("DynamicCone", function(shape, w, h) { var geo = new go.Geometry(); // 读取自定义圆锥角度(默认60度,转为弧度) var coneAngle = shape.coneAngle || Math.PI / 3; // 计算圆锥底边半宽:高度 × tan(半角) var halfBaseWidth = h * Math.tan(coneAngle / 2); // 限制宽度不超出给定的w范围 var actualHalfWidth = Math.min(halfBaseWidth, w / 2); // 按比例适配贝塞尔控制点偏移量 var cpxOffset = KAPPA * actualHalfWidth / (w/2); var cpyOffset = KAPPA * 0.1 * h; // 路径起始于底边左侧 var fig = new go.PathFigure(w/2 - actualHalfWidth, h * 0.9, true); geo.add(fig); // 绘制顶点连线 fig.add(new go.PathSegment(go.PathSegment.Line, w/2, 0)); // 绘制底边右侧连线 fig.add(new go.PathSegment(go.PathSegment.Line, w/2 + actualHalfWidth, h * 0.9)); // 绘制底部右侧贝塞尔圆角 fig.add(new go.PathSegment(go.PathSegment.Bezier, w/2, h, w/2 + actualHalfWidth, (0.9 + cpyOffset/h) * h, w/2 + cpxOffset, h)); // 绘制底部左侧贝塞尔圆角并闭合路径 fig.add(new go.PathSegment(go.PathSegment.Bezier, w/2 - actualHalfWidth, h * 0.9, w/2 - cpxOffset, h, w/2 - actualHalfWidth, (0.9 + cpyOffset/h) * h).close()); // 调整自适应定位点 geo.spot1 = new go.Spot(0.5 - actualHalfWidth/w, 0.5); geo.spot2 = new go.Spot(0.5 + actualHalfWidth/w, 0.97); return geo; });
- 使用动态圆锥
创建Shape时通过coneAngle属性传入弧度值设置角度:
// 创建45度(π/4弧度)的圆锥 var coneShape = new go.Shape({ figure: "DynamicCone", width: 100, height: 150, coneAngle: Math.PI / 4, fill: "lightblue", stroke: "darkblue" });
关键说明
- 三角函数使用弧度,需将角度转为弧度(公式:
Math.PI/180 * 角度值) - 加入宽度限制避免圆锥超出设定的尺寸范围
- 贝塞尔控制点按比例适配,保证底部圆角的视觉一致性
内容的提问来源于stack exchange,提问作者Muhammad Burhanudin
相关产品推荐
相关产品推荐

