How do I manipulate the SVG DOM and create elements?

后端 未结 1 1080
借酒劲吻你
借酒劲吻你 2020-12-04 02:47

How do I get the SVG DOM root, and start adding children to it, programmatically, instead of adding SVG elements by markup?

1条回答
  •  离开以前
    2020-12-04 03:06

    
      
    
    

    Seen in action: http://phrogz.net/SVG/create-circle.svg

    Because it can be so cumbersome to issue all those setAttribute calls, I often use a function like this:

    // Create an SVG element on another node with a set of attributes.
    // Attributes with colons in the name (e.g. 'xlink:href') will automatically
    // find the appropriate namespace URI from the SVG element.
    // Optionally specify text to create as a child node, for example
    //   createOn(someGroup,'text',{x:100,'text-anchor':'middle'},"Hello World!");
    function createOn(root,name,attrs,text){
      var doc = root.ownerDocument, svg = root;
      while (svg.tagName!='svg') svg = svg.parentNode;
      var el = doc.createElementNS(svg.namespaceURI,name);
      for (var a in attrs){
        if (!attrs.hasOwnProperty(a)) continue;
        var p = a.split(':');
        if (p[1]) el.setAttributeNS(svg.getAttribute('xmlns:'+p[0]),p[1],attrs[a]);
        else el.setAttribute(a,attrs[a]);
      }
      if (text) el.appendChild(doc.createTextNode(text));
      return root.appendChild(el);
    }
    

    In action, the above file becomes more simply:

    
      
    
    

    Seen in action: http://phrogz.net/svg/create-circle-2.svg

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