我正在尝试创建一个日历(24 小时,7 个工作日),它显示每小时的某些数据点。由于我没有每小时的数据(因此不想将其余部分留空),因此我想用空矩形预先填充网格。
我遇到的问题是,我知道如何通过首先创建一个空对象来解决这个问题(因此对于每个工作日,我们创建 24 个数据点,总共 7 * 24)。但在我看来,这是一种相当低效的方法,它会减慢网站的速度,因为我们首先必须创建空对象。
这是当前代码:
var test = svg.selectAll(".time")
.data(emptyarray)
.enter().append("rect")
.attr("x", function(d) { return (d.time) * gridSize; })
.attr("y", function(d) { return (d.weekday) * gridSize; })
.attr("rx", 4)
.attr("ry", 4)
.attr("class", "bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.style("fill", colors[0]);
我尝试了几种解决方案,即一些 for 循环结构,但这导致了它只在某个位置显示 1 个矩形,而不是用矩形填充整个网格的问题。关于如何解决这个问题有什么建议吗?
谢谢!
最佳答案
简单过滤emptyarray
怎么样?绘图之前?
例如
var test = svg.selectAll(".time")
.data(emptyarray.filter(function(d){ return d !== undefined; }))
.enter().append("rect")
.attr("x", function(d) { return (d.time) * gridSize; })
.attr("y", function(d) { return (d.weekday) * gridSize; })
.attr("rx", 4)
.attr("ry", 4)
.attr("class", "bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.style("fill", "green");
如果您想要空矩形(SVG DOM 中的空 <rect>
比空 javascript 对象更浪费资源),您可以:
var test = svg.selectAll(".time")
.data(emptyarray)
.enter().append("rect")
.attr("x", function(d, i) {
return d === undefined ? i*gridSize : (d.time) * gridSize;
})
.attr("y", function(d, i) {
return d === undefined ? i*gridSize : (d.weekday) * gridSize;
})
.attr("rx", 4)
.attr("ry", 4)
.attr("class", function(d){
return d === undefined ? "invisible": "bordered";
})
.attr("width", gridSize)
.attr("height", gridSize)
.style("fill", "green");
添加CSS
.invisible{
visibility: hidden;
}
如果您还没有阅读过,我建议您阅读 D3 time scale documentation 。您可能会考虑从时间到像素位置映射的比例,例如。
var x = d3.time.scale()
.range([0, width]);
还有d3.time.week
等等,它可以将日期巧妙地“舍入”到最近的间隔(例如周)。
关于javascript - 在 D3.js 中用空矩形填充网格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31635460/