javascript 有没有办法使用Javascript合并两个路径元素(svg)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5892549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to merge two path elements (svg) using Javascript?
提问by Jesufer Vn
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?
我使用 SVG 绘制了两条路径线,并将这些元素保存到我的 javascript 代码中的两个变量中:“Line1”和“Line2”,我需要将这两行合并为一个路径元素。有没有办法这样做?
采纳答案by robertc
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:
您的路径是相对(小写字母)还是绝对(大写字母)定义的?如果是绝对的,连接两条路径是微不足道的,只需附加d
属性的值。如果你有两条这样的路径:
<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;"/>
Then this JavaScript code:
然后这个 JavaScript 代码:
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;"/>
Here's a jsFiddle, it works in Firefox 4 (needs an HTML5 parser so you can have inline SVG).
这是一个 jsFiddle,它适用于 Firefox 4(需要一个 HTML5 解析器,以便您可以拥有内联 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.
如果您的路径是相对的,那么您将不得不在附加路径之间添加一些内容,以便第二个路径从正确的位置开始。