2011-11-30 88 views

回答

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

在行動中看到:http://phrogz.net/SVG/create-circle.svg

因爲它可以這麼麻煩發行所有這些setAttribute電話,我經常使用這樣的功能:

// 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); 
} 

在行動,上述文件變得更簡單:

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

見效: http://phrogz.net/svg/create-circle-2.svg

+0

只是注意'版本'和'baseProfile'是相當無用的。 –

+0

@ErikDahlström哦?很高興知道。鑑於你是誰,我想我必須信任你。我之前一直信任[本頁]的建議(https://jwatt.org/svg/authoring/),其中說,_「相反,始終在根標記中包含'version'和'baseProfile'屬性,並且爲其分配適當的值「_」。 – Phrogz