d3 - 将元素附加到外部SVG文件

whi*_*ler 3 svg d3.js

我有一个图形,我想加载作为我的d3可视化的背景(或简单地作为svg我可以附加circle元素).插图是svg格式的.我试图以html这样的方式将它加载到我的文件中,这样我就可以将元素(例如圆圈)附加到文件的(或顶部)svgdiv它所在的文件中.这是我有两种方法尝试:

<script>

d3.xml("bal.svg", "image/svg+xml", function(xml) {
  document.body.appendChild(xml.documentElement);
});

var circle = svg.append("circle")
                .attr("cx", 100)
                .attr("cy", 100)
                .attr("r", 20)
                .style("fill", "red");

</script>
Run Code Online (Sandbox Code Playgroud)

svg图像看起来非常精细,但没有圆圈出现.在Firefox中,html外部svg文件显示为:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" 
width="250px" height="250px" viewBox="0 0 250 250" 
enable-background="new 0 0 250 250" xml:space="preserve">
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

<div id="htmlEmbed"></div>

<script>

d3.select("#htmlEmbed")
.append("object")
.attr("data", "tba2.svg")
.attr("width", 500)
.attr("height", 500)
.attr("type", "image/svg");

d3.select("#htmlEmbed")
.append("circle")
.attr("cx", 600)
.attr("cy", 600)
.attr("r", 20)
.style("fill", "red"); 
Run Code Online (Sandbox Code Playgroud)

同样,svg图像看起来非常精细,但没有圆圈出现.在这种情况下,html在浏览器中显示为:

<object width="500" height="500" data="tba2.svg" type="image/svg">
#document
<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" 
width="500px" height="500px" viewBox="0 0 250 250" 
enable-background="new 0 0 250 250" xml:space="preserve"> … </svg>
</object>
Run Code Online (Sandbox Code Playgroud)

我觉得这应该是相当简单的,但我不知道.任何帮助将不胜感激.

Lar*_*off 9

您尝试过的代码存在两个问题.首先,您需要svg正确定义,第二,您需要执行在加载SVG后修改SVG的代码.由于异步性质d3.xml,情况并非如此.

所以你需要运行的代码就是这个.

d3.xml("http://openvz.org/images/1/17/Warning.svg", function(xml) {
  document.body.appendChild(xml.documentElement);

  var circle = d3.select("svg").append("circle")
            .attr("cx", 100)
            .attr("cy", 100)
            .attr("r", 20)
            .style("fill", "red");
});
Run Code Online (Sandbox Code Playgroud)

在这里工作小提琴(模数安全限制).