gpt4 book ai didi

javascript - 使用 javascript 将椭圆转换为路径

转载 作者:行者123 更新时间:2023-12-01 00:25:51 25 4
gpt4 key购买 nike

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

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

<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 个贝塞尔曲线的控制点位置的图像:

enter image description here

更新

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>

关于javascript - 使用 javascript 将椭圆转换为路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59011294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com