我有一個圖形我想加載作爲我的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'。 –