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

前端 未结 1 1937
长情又很酷
长情又很酷 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:

    <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:

    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).

    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)
提交回复
热议问题