2013-01-18 206 views
2

我寫了一個小example page,看起來像這樣:如何使用純Javascript將元素添加到嵌入式SVG?

<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
     <title>IGO&nbsp;&ndash;&nbsp;IRC Go</title> 
     <link rel="stylesheet" type="text/css" href="igo.css" /> 
     <script type="text/javascript" src="igo.js"></script> 
    </head> 
    <body> 
     <h1 onclick="makeCircle()">IGO&nbsp;&ndash;&nbsp;IRC Go</h1> 
     <svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="board" 
      width="4" height="4" viewBox="0 0 4 4"> 
     <!-- content will be generated by script --> 
     </svg> 
     <div id="foo"></div> 
    </body> 
</html> 

igo.js看起來是這樣的:

function makeCircle() { 
    var circle = document.createElement("circle"); 
    var board = document.getElementById("board"); 
    circle.cx = 4; 
    circle.cy = 4; 
    circle.r = 4; 
    circle.fill = "lime"; 
    board.appendChild(circle); 
} 

的問題是:它不工作;圓圈不顯示。你可以幫我嗎?

回答

4

請看看以下網址: http://blog.blazingcloud.net/2010/09/17/svg-scripting-with-javascript-part-1-simple-circle/

你應該使用如下代碼:

var c2 = document.createElementNS("http://www.w3.org/2000/svg", "circle"); 
c2.setAttribute("cx", "250"); 
c2.setAttribute("cy", "100"); 
c2.setAttribute("r", "60"); 
c2.setAttribute("fill", "#996699"); 
c2.setAttribute("stroke", "#AA99FF"); 
c2.setAttribute("stroke-width", "7"); 
mySvg.appendChild(c2); 

您正在編輯的DOM對象,而不是通過瀏覽器使用的屬性。

直播示例:http://jsfiddle.net/CJrrz/

+0

謝謝!我應該嘗試一下。 – fuz

+0

在小提琴上增加了現場示例。 – Niels

相關問題