使用 javascript 将椭圆转换为路径

Ellipse to path convertion using javascript

<ellipse cx="150" cy="80" rx="100" ry="50"   style="fill:yellow;stroke:purple;stroke-width:2" />

如何将 svg 椭圆标记转换为 svg 路径 In javascript

<path fill-rule="evenodd" clip-rule="evenodd" fill="#DE1414" d="M170.821,..........z"></path>

路径的 d 属性由 4 条三次贝塞尔曲线组成,每个象限一条。为了计算控制点位置,我使用常数 kappa=0.5522847498;。我从 Drawing a circle with Bézier Curves

中获取了 kappa 的值

函数getD(cx, cy, rx, ry)将椭圆cx和cy的中心坐标以及椭圆rx和ry的半径作为属性

function getD(cx, cy, rx, ry) {
        var kappa=0.5522847498;
        var ox = rx * kappa; // x offset for the control point
        var oy = ry * kappa; // y offset for the control point 
        let d = `M${cx - rx},${cy}`;
            d+= `C${cx - rx}, ${cy - oy}, ${cx - ox}, ${cy - ry}, ${cx}, ${cy - ry},`
            d+= `C${cx + ox}, ${cy - ry}, ${cx + rx}, ${cy - oy}, ${cx + rx}, ${cy},`
            d+= `C${cx + rx}, ${cy + oy}, ${cx + ox}, ${cy + ry}, ${cx}, ${cy + ry},`
            d+= `C${cx - ox}, ${cy + ry}, ${cx - rx}, ${cy + oy}, ${cx - rx}, ${cy},`
            d+= `z`;
       return d;
  }

thePath.setAttributeNS(null, "d", getD(150, 80, 100, 50))
<svg>
<ellipse cx="150" cy="80" rx="100" ry="50"   style="fill:yellow;stroke:purple;stroke-width:2" />
<path id="thePath" d="" style="fill:red"/>
</svg>

这张图片显示了用于绘制路径椭圆的 4 个贝塞尔曲线的控制点位置:

更新

OP 正在评论:

Actually this code working for conversion of ellipse to path but the height,width,x and y position of path different from previous ellipse.

为了证明情况并非如此,我在椭圆和路径的边界框之间添加了一个比较:

console.log("ellipse",el.getBBox())
console.log("path",pth.getBBox())
<svg>
<ellipse id="el" cx="150" cy="80" rx="100" ry="50" style="fill:yellow;stroke:purple;stroke-width:2"></ellipse>
<path id="pth" d="M50,80C50, 52.385762510000006, 94.77152502000001, 30, 150, 30,C205.22847498, 30, 250, 52.385762510000006, 250, 80,C250, 107.61423749, 205.22847498, 130, 150, 130,C94.77152502000001, 130, 50, 107.61423749, 50, 80,z" style="fill:red"></path>
</svg>