2016-12-25 184 views
1

我很難搞清楚如何使用數據集中的鏈接將圖像置於圓圈內。我知道需要一種模式才能將圖像添加到節點 - related即使在引入節點和數據之前,關於此主題的SO問題附加了def,pattern和image元素。如何在D3js中動態地將圖像添加到圓形

就我而言,我無法找到出路,因爲數據是動態添加到每個節點的附加功能,選擇裏面的標籤。下面的代碼的項目,每一個黑點是爲了遏制昆蟲的不同的圖像(URL在TSV文件):https://plnkr.co/edit/Ydrxogbfm9JvqrgeQaQ6?p=preview

我試圖改變在身體標記與下面的代碼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的初學者。節日快樂

回答

2

您不能將<defs><pattern><image>附加到圓圈中。這是行不通的。

取而代之的是,你必須根據自己的唯一ID創建<defs>,追加圖案和圖像,並填寫圓:

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("")) + ")" 
    }); 
} 

這是你更新plunker:http://plnkr.co/edit/WLC2ihpzsjDUgcuu910O?p=preview

PS:你的代碼正在工作,但我不得不說,你的for循環在D3 dataviz中是不必要的(甚至是尷尬的)。這不是訪問數據的D3方式。因此,我建議你完全重構你的代碼塊。

+0

我試圖得到通過添加.forEach擺脫外的for循環循環,以'.data',可惜我無法得到它的工作。 – st4rgut