基于两点与圆弧半径求路径圆弧中点,解决getPointAtLength废弃问题
解决圆弧中点计算问题(替代废弃的
getPointAtLength()方法) 既然getPointAtLength()已经被废弃,咱们直接用几何计算来求圆弧中点,完全不依赖SVG的路径API,这样更稳定也更通用。下面是具体的思路和代码实现:
核心思路
已知点A(x₁,y₁)、点B(x₂,y₂)和圆弧半径r,求中点M的步骤:
- 计算AB线段的中点C,以及AB的长度
- 计算圆心到AB线段的垂直距离d(由勾股定理可得:
d = √(r² - (AB/2)²)) - 找到AB的垂直平分线方向,确定圆心O的两个可能位置(根据圆弧的顺时针/逆时针方向选择其中一个)
- 计算OA和OB的夹角,取中间角度得到中点M的坐标
代码实现
function calculateArcMidpoint(A, B, radius, isClockwise = false) { // 步骤1:计算AB的中点C和AB长度 const Cx = (A.x + B.x) / 2; const Cy = (A.y + B.y) / 2; const ABLength = Math.hypot(B.x - A.x, B.y - A.y); // 检查半径是否合法(半径必须大于等于AB长度的一半) if (radius < ABLength / 2) { throw new Error("Radius must be at least half the length of AB"); } // 步骤2:计算圆心到AB的垂直距离d const d = Math.sqrt(radius ** 2 - (ABLength / 2) ** 2); // 步骤3:计算AB的垂直方向向量 // AB的方向向量是(B.x - A.x, B.y - A.y),垂直向量为(-(B.y - A.y), B.x - A.x) 或 ((B.y - A.y), -(B.x - A.x)) const perpX = -(B.y - A.y); const perpY = B.x - A.x; // 归一化垂直向量 const perpLength = Math.hypot(perpX, perpY); const normalizedPerpX = perpX / perpLength; const normalizedPerpY = perpY / perpLength; // 确定圆心O的坐标(根据顺时针/逆时针选择方向) const Ox = Cx + (isClockwise ? -d : d) * normalizedPerpX; const Oy = Cy + (isClockwise ? -d : d) * normalizedPerpY; // 步骤4:计算OA和OB的角度,取中间角度得到中点M const angleOA = Math.atan2(A.y - Oy, A.x - Ox); const angleOB = Math.atan2(B.y - Oy, B.x - Ox); // 计算中间角度(处理跨0度的情况) let midAngle; if (isClockwise) { midAngle = angleOA - (angleOA - angleOB + 2 * Math.PI) % (2 * Math.PI) / 2; } else { midAngle = angleOA + (angleOB - angleOA + 2 * Math.PI) % (2 * Math.PI) / 2; } // 计算中点M的坐标 const Mx = Ox + radius * Math.cos(midAngle); const My = Oy + radius * Math.sin(midAngle); return { x: Mx, y: My }; } // 示例使用 const pointA = { x: 0, y: 0 }; const pointB = { x: 4, y: 0 }; const arcRadius = 3; const midpoint = calculateArcMidpoint(pointA, pointB, arcRadius, false); // 逆时针圆弧 console.log("圆弧中点M坐标:", midpoint);
说明
isClockwise参数用来指定圆弧的方向:false表示逆时针(默认),true表示顺时针- 代码会先检查半径是否合法(必须大于等于AB长度的一半,否则无法构成圆弧)
- 完全不依赖SVG的任何API,避免了废弃方法的问题,同时也能在非SVG场景下使用
内容的提问来源于stack exchange,提问作者user11931243
相关产品推荐
相关产品推荐

