在不更改形状的情况下将任何 SVG 路径拆分为多个部分



我是使用javacript进行SVG操作的新手。我想将任何类型的 SVG 路径拆分为N个段,以便原始形状保持不变,但向路径添加了额外的点。我成功地使用贝塞尔JS插件将一条立方曲线转换为N个点,并使用.getLUT(steps)函数。

我能够使用 Flatten.js 将任何 SVG 元素转换为路径。

在链接中 http://bl.ocks.org/bycoffe/18441cddeb8fe147b719fab5e30b5d45 一条路径是无缝拆分的,但我正在努力使用 DOM 中 SVG 元素中的现有路径来实现相同的目标。

这是我的代码:

...
<svg id="svg" style="border: 1px solid" width="500" height="500">
<!--The below is an actual rectangle drawn in illustrator-->
<rect x="0.5" y="0.5" width="234" height="125" style="fill:#fff"/>
<path d="M317,107V231H84V107H317m1-1H83V232H318V106Z" transform="translate(-83 -106)"/>
</svg>
...
<script type="text/javascript">
//this converts the <rect> and <path> into a more clean path d attribute
//the above code produces the below d attribute points
//for <rect> - M0.5, 0.5 L 234.5,0.5 L 234.5, 125.5 L 0.5, 125.5 L 0.5, 0.5 Z
//for <path> - M234, 1 L 234, 125 L 1, 125 L 1, 1 L 234, 1 m 1, -1 L 0,0 L 0, 126 L 235, 126 L 235,0 Z
flatten(document.getElementById('svg')); 

</script>

我能够通过使用函数document.getElementById('#path').getTotalLength();获取路径的总长度并使用 document.getElementById('#path'(.getPointAtLength(i( 生成新的 d 点来实现结果; 使用以下代码

the_path = document.getElementById('#path');
let l = the_path.getTotalLength();
let p = the_path.getPointAtLength(0);
let d = `M${p.x} ${p.y}`;

for(let i = (l/num);i<=l;i+=(l/num)){
p = the_path.getPointAtLength(i);
d += `L${p.x} ${p.y}`;
}

最新更新