Appending path child within SVG Using Javascript

前端 未结 2 1318
粉色の甜心
粉色の甜心 2020-12-24 06:29

Good Day,

I am having incredible difficulty in creating a path and displaying it using \"appendChild\" within an SVG element.

I have to be missing somethin

相关标签:
2条回答
  • 2020-12-24 07:14

    There are two issues:

    1. As already pointed out, you have to use the full namespace uri, so in this case:

      newpath = document.createElementNS('http://www.w3.org/2000/svg',"path");  
      
    2. Attributes also need to be set with namespace in mind. The good news is that you can pass in null as the namespace uri, so:

      newpath.setAttributeNS(null, "d", "M 1,97.857143 C 19.285714,96.428571 24.016862,131.64801 90.714286,132.85714 140.78762,133.7649 202.79376,66.16041 202.79376,66.16041");
      

    Also, here are two ways to make dealing with the svg namespace easier (assuming that it is a standalone svg, not embedded in HTML):

    • To refer to the svg element, instead of giving it an ID, you can use document.rootElement.
    • document.rootElement.getAttribute(null, "xmlns") returns an empty string (while requesting other attributes does work using this method. Instead, use document.rootElement.namespaceURI.

    So in your code, you could make the following rewrites:

    From:

     newpath = document.createElementNS("http://www.w3.org/2000/svg","path");
    

    To:

     newpath = document.createElementNS(document.rootElement.namespaceURI,"path");  
    

    And to append the element, you can go from:

    document.getElementById("fullPageID").appendChild(newpath);
    

    to:

    document.rootElement.appendChild(newpath);
    

    So the final script would be:

    newpath = document.createElementNS(document.rootElement.namespaceURI,"path");  
    newpath.setAttributeNS(null, "id", "pathIdD");  
    newpath.setAttributeNS(null, "d", "M 1,97.857143 C 19.285714,96.428571 24.016862,131.64801 90.714286,132.85714 140.78762,133.7649 202.79376,66.16041 202.79376,66.16041");  
    newpath.setAttributeNS(null, "stroke", "black"); 
    newpath.setAttributeNS(null, "stroke-width", 3);  
    newpath.setAttributeNS(null, "opacity", 1);  
    newpath.setAttributeNS(null, "fill", "none");
    
    document.rootElement.appendChild(newpath);
    
    0 讨论(0)
  • 2020-12-24 07:22

    The namespace needs to be "http://www.w3.org/2000/svg", not "SVG" in the createElementNS call.

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