我有一个图形我想加载作为我的d3可视化背景(或简单地作为我可以附加circle
元素的svg
)。插图格式为svg
。我试图将它加载到我的html
文件中,以便允许我将元素(如圆圈)添加到svg
文件或其所在的div
(或顶部)。以下是两个我尝试过的方法:d3 - 将元素添加到外部SVG文件
<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中,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">
我也曾尝试:
<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>
我有一种感觉,这应该是相当简单的事,但我不知道。任何帮助将不胜感激。
在你的第一个例子中,你没有告诉我们如何定义'svg'。请注意,您可能需要将svg命名空间添加到您追加的任何元素(即'.append(“svg:circle”)')。 –
感谢您的回复。在第一个例子中,我没有明确定义svg。我的假设是,通过执行svg.append(“circle”),代码将选择图像的svg元素(由于前面的行而出现在html中)。我怎样才能告诉它使用图像的svg?顺便说一下,如果我在文本编辑器中打开svg文件,只需将cx,cy属性的标记添加到浏览器中并将其打开,则圆形显示效果就会很好。必须有方法让d3追加这些元素,但我不知道如何让它识别图像的svg。 – whistler
D3不会基于页面上的内容神奇地分配变量。可以使用'd3.select(“svg”)''来代替'svg'。 –