Is there a way to merge two path elements (svg) using Javascript?

前端 未结 1 1938
长情又很酷
长情又很酷 2021-02-13 02:19

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 o

1条回答
  •  感动是毒
    2021-02-13 03:09

    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:

    
    
    

    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:

    
    

    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.

    0 讨论(0)
提交回复
热议问题