Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

javascript - How do I manipulate the SVG DOM and create elements?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<svg xmlns="http://www.w3.org/2000/svg">
  <script>
    var svg   = document.documentElement;
    var svgNS = svg.namespaceURI;

    var circle = document.createElementNS(svgNS,'circle');
    circle.setAttribute('cx',100);
    circle.setAttribute('cy',200);
    circle.setAttribute('r',50);
    circle.setAttribute('fill','red');
    circle.setAttribute('stroke','black');
    circle.setAttribute('stroke-width','20px');
    circle.setAttribute('stroke-opacity','0.5');

    svg.appendChild(circle);
  </script>
</svg>

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:

<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
  <script>
    var svg = document.documentElement;
    createOn(svg,'circle',{
      cx:100, cy:200, r:50,
      fill:'red', stroke:'black',
      'stroke-width':'20px', 'stroke-opacity':0.5
    });
    // …function from above…
  </script>
</svg>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...