d3 - 将元素附加到外部SVG文件 [英] d3 - Append elements to external SVG file
问题描述
我有一个图形,我想加载为我的d3可视化的背景(或简单作为 svg
,我可以追加 circle
元素)。图示为 svg
格式。我试图加载它到我的 html
文件中,这样,将允许我然后将元素(如圆)附加到(或顶部) code> svg 文件或其中的 div
。我尝试了两种方法:
I have a graphic I'd like to load as a background to my d3 visualization (or simply as an svg
that I can append circle
elements to). The illustration is in svg
format. I have tried to load it into my html
file in such a way that would allow me to then append elements (such as circles) to the (or on top of) the svg
file or to the div
that it is in. Here are two approaches I have tried:
<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
文件的 html
显示为:
The svg image appears perfectly fine, but no circle shows up. In Firefox, the html
for the external svg
file shows up as:
<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在浏览器中显示为:
Again, the svg image appears perfectly fine, but no circle shows up. In this case, the html shows in the browser as:
<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>
我觉得这应该是很直接的,但我不知道。任何帮助将非常感激。
I have the feeling this should be rather straightforward to do, but I don't know. Any help would be greatly appreciated.
推荐答案
您尝试的代码有两个问题。首先,您需要正确定义 svg
;其次,您需要执行修改SVG加载后的代码。因为 d3.xml
的异步本质,所以不是这样。
There were two issues with the code you've tried. First, you need to define svg
properly and second, you need to execute the code that modifies the SVG after it's been loaded. Because of the asynchronous nature of d3.xml
, this was not the case.
run是这个。
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");
});
Working fiddle (modulo security restrictions) here.
这篇关于d3 - 将元素附加到外部SVG文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!