[英]How to Add Image to Circle Dynamically in D3js
我很難弄清楚如何使用數據集中的鏈接將圖像放置在圓圈內。 我知道需要一種將圖像添加到節點的模式- 與該主題相關的 SO問題在引入節點和數據之前會先添加def,pattern和image元素。
就我而言,我找不到從選擇器函數中附加標簽的方法,因為數據是動態添加到每個節點的。 這是項目的代碼,每個黑點都應該包含一個不同的昆蟲圖像(URL在tsv文件中): https ://plnkr.co/edit/Ydrxogbfm9JvqrgeQaQ6?p = preview
我嘗試使用以下代碼更改body標簽中的xlink:href
:
<body>
<svg width="1000" height="600">
<defs id="mdef">
<pattern id="image" x="0" y="0" height="40" width="40">
<image x="0" y="0" width="40" height="40" ></image>
</pattern>
</defs>
</svg>
</body>
以及此代碼段中的JS代碼段添加了節點。 :
.attr('"xlink:href", function(d){return d[1];}) //d is an array and the d[1] is the link
但是,圖像沒有出現。 然后,我嘗試使用js添加模式:
for (i=0;i<insects.length;i++){
g.selectAll("circle")
.data(insects[i],function(d) {console.log(d); return d }) //each insect
.enter().append("circle")
.attr('cx', function(d,index) {return x(insects[i].length)/insects[i].length*index; })
.attr("r", 20)
.attr("cy", function(d,index){return y.bandwidth()*i})
.append('svg:defs') //adding pattern
.append('svg:pattern')
.attr('id','pattern')
.attr("x",0)
.attr("y",0)
.attr("width",40)
.attr("height",40)
.append("svg:image")
.attr("x",0)
.attr("y",0)
.attr("width",40)
.attr("height",40)
.attr("xlink:href", function(d){console.log(d[1]); return d[1];})
.style("fill", "url(#pattern)");
}
})
但我得到相同的結果。 我真的很感謝任何指針,因為我是d3的初學者。 節日快樂
您不能將<defs>
, <pattern>
和<image>
附加到圓上。 那行不通。
取而代之的是,您必須創建<defs>
,添加圖案和圖像,並根據其唯一ID填充圓圈:
var defs = g.append("defs");
defs.selectAll(".patterns")
.data(insects[i], function(d) {
return d
})
.enter().append("pattern")
.attr("id", function(d) {
return "insect" + (d[0].split(" ").join(""))
})
.attr("width", 1)
.attr("height", 1)
.append("svg:image")
.attr("xlink:href", function(d) {
return d[1]
})
.attr("width", 40)
.attr("height", 40);
g.selectAll("circle")
.data(insects[i], function(d) {
return d
})
.enter().append("circle")
.attr('cx', function(d, index) {
return x(insects[i].length) / insects[i].length * index;
})
.attr("r", 20)
.attr("cy", function(d, index) {
return y.bandwidth() * i
})
.style("fill", function(d) {
return "url(#insect" + (d[0].split(" ").join("")) + ")"
});
}
這是您更新的插件: http ://plnkr.co/edit/WLC2ihpzsjDUgcuu910O?p=preview
PS :您的代碼正在運行,但是我不得不說,在D3 dataviz中,您的for循環是不必要的(甚至很尷尬)。 這不是D3訪問數據的方式。 因此,我建議您完全重構該塊中的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.