我一直在尝试按照不同的d3.js教程创建自己的六边形网格。
我已经走到this我需要用图像替换随机颜色,我读到我需要做这样的事情:
var imagePatterns = svg.selectAll('pattern').data(data).
enter().append('pattern')
.attr('x',50)
.attr('y',50)
.attr('width',1)
.attr('height',1)
.append('image').attr("xlink:href", function(d,i){
return data[i].img;
})
.attr("x", function(d,i){
return i+100;
})
.attr("y", function(d,i){
return i+200;
})
.attr("width", 230)
.attr("height", 230)
.attr("id", function(d,i){
return 'fillImage'+i
});
我有一个包含40个图像的数据数组,半径为120的六边形的数量形成topoApi是40,我知道我需要设置我的图像一些如何到每个六边形的中心,但是上面的代码我只有看到生成的html中的模式,但没有别的
首先我需要在屏幕上显示图像,然后我应该定位它们,请帮助
答案 0 :(得分:0)
我已经找到了填充六边形的图像,这个图像符合我的建议,所以我将接受我自己的答案。可能会发布未来的解决方案。
请注意:在我的情况下,我只需要填充相对位于网格中心的8个六边形的图像,我不需要做任何计算我只知道我有44个六边形而我需要填充网格编号为20到27的路径。我的图像数据集包含8个图像,我用它来为我需要填充的每个六边形创建多个图像模式
var imagePatterns = d3.select("#imagesContainer").append('svg').selectAll('pattern')
.data(data)
.enter().append('defs').append('pattern')
.attr('id', function (d, i) {
return 'fillImage' + (19 + i);
})
.attr('patternUnits', 'userSpaceOnUse')
.attr('width', 190)
.attr('height', 270)
.append('image').attr("xlink:href", function (d, i) {
return d;
}).attr("x", 0)
.attr("y", 0)
.attr("width", imageWidth)
.attr("height", imageHeight);
在创建六边形几何的 hexTopology 函数中,我为要填充的路径的几何对象添加了填充属性,其他路径用白色填充。
var hexagonPaths = [20, 21, 22, 23, 24, 25, 26, 27];
geometries.forEach(function (obj, ind) {
if (hexagonPaths.indexOf(ind) > -1)
{
geometries[ind].fill = "url(#fillImage" + ind + ")";
geometries[ind].text = 'my text';
}
else
{
geometries[ind].fill ='#fff';
geometries[ind].text = '';
}
});
然后我更新了六边形的每条路径的样式
svg.append("g")
.attr("class", "hexagon")
.selectAll("path")
.data(topology.objects.hexagons.geometries)
.enter().append("path")
.attr("d", function (d) {
return path(topojson.feature(topology, d));
}).style('fill', function (d, i) {
return d.fill;
});
最后两点: