有没有办法使用Javascript合并两个路径元素(svg)? [英] Is there a way to merge two path elements (svg) using Javascript?

查看:103
本文介绍了有没有办法使用Javascript合并两个路径元素(svg)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SVG绘制了两条路径,我在javascript代码中将这些元素保存为两个变量:'Line1'和'Line2',我需要将这两行合并为一个单独的路径元素。有没有办法这样做?

I have drawn two path lines using SVG and I've saved these elements into two variables in my javascript code: 'Line1', and 'Line2', and I need to merge the two lines into one single path element. Is there a way to do so?

推荐答案

您的路径是相对(小写字母)还是绝对(大写字母)?如果是绝对的,加入两个路​​径是微不足道的,只需附加 d 属性的值。如果您有两条这样的路径:

Are your paths defined relatively (small letters) or absolutely (capitals)? If absolute, joining two paths is trivial, just append the values of the d attribute. If you have two paths like this:

<path id="Line1" d="M50,50
         A30,30 0 0,1 35,20
         L100,100"
      style="stroke:#660000; fill:none;"/>
<path id="Line2" d="M110,110
         L100,0"
      style="stroke:#660000; fill:none;"/>

然后这个JavaScript代码:

Then this JavaScript code:

var Line1 = document.getElementById("Line1");
var Line2 = document.getElementById("Line2");
//Add paths together
Line1.setAttribute('d', Line1.getAttribute('d') + ' ' + Line2.getAttribute('d'));
//Remove unnecessary second path
Line2.parentNode.removeChild(Line2);

会导致你有这样的单一路径:

Will lead to you having a single path like this:

<path id="Line1" d="M50,50
         A30,30 0 0,1 35,20
         L100,100 M110,110
         L100,0"
      style="stroke:#660000; fill:none;"/>

这是一个jsFiddle ,它适用于Firefox 4(需要一个HTML5解析器,因此你可以使用内联SVG)。

Here's a jsFiddle, it works in Firefox 4 (needs an HTML5 parser so you can have inline SVG).

如果你的路径是相对的那么你'必须在附加路径之间添加一些内容,以便第二个路径在正确的位置开始。

If your paths are relative then you're going to have to add something between the appended paths so that the second one starts in the correct place.

这篇关于有没有办法使用Javascript合并两个路径元素(svg)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆