如何在D3js中动态地将图像添加到圆形
问题描述:
我很难搞清楚如何使用数据集中的链接将图像置于圆圈内。我知道需要一种模式才能将图像添加到节点 - 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的初学者。节日快乐
答
您不能将<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方式。因此,我建议你完全重构你的代码块。
我试图得到通过添加.forEach摆脱外的for循环循环,以'.data',可惜我无法得到它的工作。 – st4rgut