2

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>

这是带有 javascript 的 html,我尝试使用 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 中添加一个像 circle 这样的新元素?

4

2 回答 2

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

于 2013-07-11T21:04:41.320 回答
0

我看到你的代码有两个问题:

  1. 选择你的元素:你正在使用document.getElementByIDwith D3.select,这是不必要的 - 你可以使用CSS 选择器选择只有 D3 的元素:

    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/

于 2013-03-10T17:20:05.223 回答