【问题标题】:Splitting any SVG path into pieces without changing the shape在不改变形状的情况下将任何 SVG 路径分割成片段
【发布时间】:2020-06-26 11:11:22
【问题描述】:

我是使用 javacript 操作 SVG 的新手。我想将任何类型的 SVG 路径拆分为 N 个段,以便原始形状保持不变,但在路径中添加了额外的点。我使用Bezier JS 插件和.getLUT(steps) 函数成功地将单个三次曲线转换为N 个点。

而且我可以使用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>

【问题讨论】:

  • 如果你能成功地将单条三次曲线转换成 N 个点,你可以尝试转换所有命令(除了移动到命令 (M,m) 和关闭路径命令 (Z ,z)) 到三次贝塞尔曲线。
  • 那么,插件 Beizer.js 将具有 d = M100 25 C 10 90 110 100 150 195 的三次曲线路径转换为 ​​M100 25 76.69 44.82 65.40 61.72 64.07 76.85 70.64 91.36 83.05 106.41 99.25 123.14 117.18 142.72 134.78 166.28 150 195 那么对于划分我需要循环到路径 d 属性中的每个 C 点吗?跨度>
  • 您评论中的第二个 d 属性在我看来就像一条折线。
  • 是三次曲线转换成多个Lineto点。请在可视化工具中查看svg-path-visualizer.netlify.app/…

标签: javascript svg bezier vector-graphics


【解决方案1】:

我能够通过使用函数 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}`;
}

【讨论】:

猜你喜欢
  • 2018-06-20
  • 1970-01-01
  • 2019-07-16
  • 2017-10-20
  • 2016-12-26
  • 2021-08-17
  • 1970-01-01
  • 2020-05-16
  • 2018-04-24
相关资源
最近更新 更多