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

标签 javascript svg ellipse path.js

<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/

相关文章:

css - SVG <animate> 从 0 的偏移量不起作用

javascript - SVG 图像无法在 Internet Explorer 11 的 echarts 工具箱中呈现

python - 使用 matplotlib.pyplot (Python) 绘制椭圆

javascript - 使用 Graph API 获取视频源 URL Facebook

javascript - xhr.getAllResponseHeaders() 在 IPHONE Safari 浏览器中未定义

css - 从 CSS3 动画 SVG 创建动画 gif

c++ - 椭圆旋转不居中

r - 在 R Plotly 中使用曲面椭圆绘制 Ellipse3d

javascript - Jquery 到原型(prototype)

javascript - 不支持 Phaser 全屏 Api