2013-03-10 22 views
2

svg文檔被嵌入爲文件。如何從嵌入的extern svg文件初始化d3 svg元素並對其進行操作

SVG文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<!-- Created with Inkscape (http://www.inkscape.org/) --> 

<svg 
    xmlns:dc="http://purl.org/dc/elements/1.1/" 
    xmlns:cc="http://creativecommons.org/ns#" 
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
    xmlns:svg="http://www.w3.org/2000/svg" 
    xmlns="http://www.w3.org/2000/svg" 
    xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" 
    xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" 
    width="64px" 
    height="64px" 
    id="svgPic" 
    version="1.1" 
    inkscape:version="0.48.4 r9939" 
    sodipodi:docname="New document 18"> 
    <g 
    id="curvLayer" 
    inkscape:label="Curv" 
    inkscape:groupmode="layer"> 
    <path 
     style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" 
     d="M 2.0162099,44.937652 C 19.928085,44.362124 23.033712,29.671999 33.839655,29.657316 44.913406,29.332988 44.178722,15.232728 60.486296,15.244392" 
     id="path4373" 
     inkscape:connector-curvature="0" 
     sodipodi:nodetypes="ccc" /> 
    </g> 
</svg> 

,這裏是HTML與JavaScript,在那裏我試圖操縱與D3的SVG。但沒有成功。

<body> 
    <embed src="berg4.svg" type="image/svg+xml" id="svgpic"/> 

    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script> 

    <script type="text/javascript" charset="utf-8"> 

    var subdoc = document.getElementById("svgPic").getSVGDocument(); 
    var curvLayer = subdoc.getElementById("curvLayer"); 
    var myPoint = d3.select("#curvLayer").append("svg:circle") 
      .attr("cx", x) //e.g. x = 100 
      .attr("cy", y) //e.g. y = 100 
      .attr("r", 4.5); 
    </script> 
</body> 

問題是,如何將一個新的元素像圓圈添加到這個svg?

回答

0

有兩個問題我與你的代碼中看到:

  1. 選擇你的元素:你用D3.select一起使用document.getElementByID,這是聯合國必要的 - 你可以使用選擇,只有D3元素CSS selectors

    d3.select("#curvLayer") 
    
  2. 設置cxcy屬性:您正在將您的附加圓圈cxcy屬性設置爲'x'和'y',但這些在您的代碼中以前未定義。嘗試設置爲靜態值或定義x和y之前:

    .append("circle") 
        .attr("cx", 10) 
        .attr("cy", 10) 
        .attr("r", 4.5); 
    

的jsfiddle有由這些更新:http://jsfiddle.net/qAHC2/308/

+0

的主要問題在這裏,該SVG是EXTERN文件。因此,我不能簡單地通過'd3.select(「#curvLayer」)' – Mark 2013-03-11 09:36:51

+0

來訪問id。爲了避免同樣的問題,我將問題升級。 – Mark 2013-03-11 12:53:43

+1

這可能有所幫助:http://stackoverflow.com/questions/3346106/accessing-a-dom-object-defined-in-an-external-svg-file – Josh 2013-03-11 18:23:45

0

的技巧是,你需要給D3的外部SVG的根元素。這可以爲您的例子就像這樣:

var svgRoot = document.getElementById('svgpic').getSVGDocument().documentElement; 
d3.select(svgRoot).select("#curvLayer").append("circle") 
              .attr("cx", 10) 
              .attr("cy", 10) 
              .attr("r", 4.5); 

顯然爲Firefox,你可能需要使用contentDocument代替getSVGDocument()