【问题标题】:Ellipse to path convertion using javascript使用javascript的椭圆到路径转换
【发布时间】:2019-11-23 19:19:20
【问题描述】:
<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>

【问题讨论】:

  • 转换成两条弧线('a' or 'A')?
  • 是否可以将椭圆转换为路径d属性?
  • ...弧线是路径中可用的命令之一,通过 a 或 A。

标签: javascript svg ellipse path.js


【解决方案1】:

路径的 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 正在评论:

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

为了证明不是这样,我在椭圆的边界框和路径之间添加了一个比较:

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>

【讨论】:

  • 谢谢 enxaneta。路径转换工作完美,但路径的位置没有改变。
  • 恐怕我听不懂你。椭圆和路径完全重叠。你能解释一下到底什么没有改变吗?
  • 实际上这段代码可以将椭圆转换为路径,但路径的高度、宽度、x 和 y 位置与之前的椭圆不同。
猜你喜欢
  • 1970-01-01
  • 2014-12-18
  • 1970-01-01
  • 2016-09-19
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多