使用 javascript 将椭圆转换为路径

kar*_*out 1 javascript svg ellipse path.js

<ellipse cx="150" cy="80" rx="100" ry="50"   style="fill:yellow;stroke:purple;stroke-width:2" />
Run Code Online (Sandbox Code Playgroud)

如何在 javascript 中将 svg 椭圆标签转换为 svg 路径

<path fill-rule="evenodd" clip-rule="evenodd" fill="#DE1414" d="M170.821,..........z"></path>
Run Code Online (Sandbox Code Playgroud)

enx*_*eta 5

路径的 d 属性由 4 条三次 B\xc3\xa9zier 曲线组成,每个象限一条。为了计算控制点位置,我使用常数kappa=0.5522847498;我从用 B\xc3\xa9zier 曲线绘制圆中获取 kappa 值

\n

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

\n

\r\n
\r\n
function getD(cx, cy, rx, ry) {\n        var kappa=0.5522847498;\n        var ox = rx * kappa; // x offset for the control point\n        var oy = ry * kappa; // y offset for the control point \n        let d = `M${cx - rx},${cy}`;\n            d+= `C${cx - rx}, ${cy - oy}, ${cx - ox}, ${cy - ry}, ${cx}, ${cy - ry},`\n            d+= `C${cx + ox}, ${cy - ry}, ${cx + rx}, ${cy - oy}, ${cx + rx}, ${cy},`\n            d+= `C${cx + rx}, ${cy + oy}, ${cx + ox}, ${cy + ry}, ${cx}, ${cy + ry},`\n            d+= `C${cx - ox}, ${cy + ry}, ${cx - rx}, ${cy + oy}, ${cx - rx}, ${cy},`\n            d+= `z`;\n       return d;\n  }\n\nthePath.setAttributeNS(null, "d", getD(150, 80, 100, 50))
Run Code Online (Sandbox Code Playgroud)\r\n
<svg>\n<ellipse cx="150" cy="80" rx="100" ry="50"   style="fill:yellow;stroke:purple;stroke-width:2" />\n<path id="thePath" d="" style="fill:red"/>\n</svg>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

这是一张显示用于绘制路径椭圆的 4 个 B\xc3\xa9ziers 控制点位置的图像:

\n

在此输入图像描述

\n

更新

\n

OP 评论道:

\n
\n

实际上,此代码用于将椭圆转换为路径,但路径的高度、宽度、x 和 y 位置与之前的椭圆不同。

\n
\n

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

\n

\r\n
\r\n
console.log("ellipse",el.getBBox())\nconsole.log("path",pth.getBBox())
Run Code Online (Sandbox Code Playgroud)\r\n
<svg>\n<ellipse id="el" cx="150" cy="80" rx="100" ry="50" style="fill:yellow;stroke:purple;stroke-width:2"></ellipse>\n<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>\n</svg>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n