在 D3 中,我習慣于從空白 div 創建視覺效果。但是,我正在努力解決以下問題。
我有一個只有 3 個矩形的 svg 檔案( https://raw.githubusercontent.com/gangrel11/samplefiles/main/d3 task1.svg )。
我想要做的是將 3 個新形狀(圓圈)附加到每個現有矩形,以便它們出現在每個矩形的中心。
這就是我要去的地方:
const svgUrl = "https://raw.githubusercontent.com/gangrel11/samplefiles/main/d3 task1.svg"
d3.xml(svgUrl).then(render);
function render(svg) {
// add svg
d3.select("body").node().append(svg.documentElement)
var svg = d3.select("body").append("svg");
svg.selectAll("rect")
.append("rect")
.attr("width", 20)
.attr("height", 20)
.attr("x", 20)
.attr("y", 10)
.attr("fill", "red")
}
這是我的jsfiddle
uj5u.com熱心網友回復:
你有幾個問題:
- 您正在添加另一個 svg 元素,而不是使用現有的元素。我的建議正在改變:
d3.select("body").append("svg");
至
d3.select("body").select("svg #layer1");
- 請注意,我還針對要轉換的
g元素#layer1。
- 您嘗試將元素附加
rect到rect元素,但 svg 不知道如何在其中繪制rect-rect此語法無效。相反,您可以使用該方法定位每個元素并使用他的位置.each,并將它們附加到所有現有的矩形之后。
代碼:函式渲染(SVG){
// add svg
d3.select("body").node().append(svg.documentElement)
var svg = d3.select("body").select("svg #layer1");
svg.selectAll("rect")
.each(function (rect){
const {x, y} = this.getBoundingClientRect();
svg.append("rect")
.attr("width", 20)
.attr("height", 20)
.attr("x", this.getAttribute('x'))
.attr("y", this.getAttribute('y'))
.attr("fill", "red");
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/491663.html
標籤:d3.js
上一篇:D3.js樹形圖錯誤的矩形大小
