我使用d3设置了数千个填充了不同图像的矩形。这是' def'的代码。一部分。
` d3.json(" data / data.json",function(error,data){
var rects = svg.selectAll("rect")
.data(data);
rects.enter()
.append("rect")
.attr("x", 0)
.attr("y", function(d,i) {
return i*barheight ;
})
.attr("class", "bar")
.attr("width", barwidth)
.attr("height", barheight)
.attr("fill", function(d){
return "rgb"+ d.rgb;
});
//更改封面图片
var def = defsvg.selectAll("def")
.data(data);
def.enter()
.append("pattern")
.attr("id", function(d){
return d.name
})
.attr("width", 1)
.attr("height", 1)
.append("image")
.attr("width", coverwidth)
.attr("height", coverheight)
.attr("xlink:href", function(d){
return "img/" + d.name;
});
cover.attr("x", 0)
.attr("y", 0)
.attr("width", coverwidth)
.attr("height", coverheight)
.append("rect")
.attr("width", coverwidth)
.attr("height", coverheight);
d3.selectAll("rect")
.on("click", function(d){
cover.attr("fill", function(){
return "url(#" + d.name + ")";
});
});
})
`
但问题是数据是14000+。相应地,文件夹中有14000个以上的项目" img"。尽管每张图片只有30kb,但对于该项目来说仍然很重要,特别是当它在移动设备上启动时。它有什么解决方案吗?谢谢!
答案 0 :(得分:1)
这是完全未经测试但在click
事件中加载图像。这里defs
是对SVG中<defs>
节点的d3选择。您不需要数据绑定并预先创建所有pattern
节点。这应创建模式,向其附加图像,等待图像加载,然后最终填充矩形。
d3.selectAll("rect")
.on("click", function(d) {
defs.append("pattern")
.attr("id", d.name)
.attr("width", 1)
.attr("height", 1)
.append("image")
.attr("onload", function() {
cover.attr("fill", "url(#" + d.name + ")");
})
.attr("width", coverwidth)
.attr("height", coverheight)
.attr("xlink:href", "img/" + d.name);
});