我有一个图形,我想把它作为d3可视化的背景(或者简单地作为一个svg,我可以将circle元素附加到其中)。插图采用svg格式。我试图将它加载到我的html文件中,这样我就可以将元素(例如圆圈)附加到(或在svg文件的顶部)或它所在的div中。以下是我尝试过的两种方法:
<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>svg图像看起来非常好,但没有出现任何圆圈。在Firefox中,外部svg文件的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">我也尝试过:
<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"); 同样,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>我觉得这应该很简单,但我不知道。任何帮助都将不胜感激。
发布于 2013-11-27 22:22:48
您尝试过的代码有两个问题。首先,您需要正确地定义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");
});工作小提琴(模块化安全限制) here。
https://stackoverflow.com/questions/20233826
复制相似问题