使用当前时间范围-36小时和当前时间时,我无法每秒移动x轴。我正在尝试从当前时间中减去一秒,并设置了一个间隔,但是我没有任何运气。
当仅尝试从当前时间中减去一秒而不是从当前时间中减去当前时间(包括当前时间减去36小时)作为当前范围时,我就获得了成功。这是一个小提琴:tp://jsfiddle.net/dtepdc/mxr51spf/。
这是我的代码:
const dataset = [
// 36 hours ago
{
start_date: moment().valueOf() - 5.04e+7,
end_date: moment().valueOf() - 4.32e+7,
coNum:"CHG0079036"
},
{
start_date: moment().valueOf() - 7.92e+7,
end_date: moment().valueOf() - 7.2e+7,
coNum:"CHG0079021"
}
];
setTimeout(realTime, 10);
setInterval(realTime, 1000);
/* ******************* REAL TIME ******************** */
function realTime(){
d3.selectAll('svg').remove();
real = [];
/* Starting time is 36 hours from the current time */
let start = moment().subtract(36, 'hours').valueOf();
let current = moment().valueOf();
/* Height & Width */
const coNumW = window.innerWidth,
coNumH = window.innerHeight,
margin = {top: coNumH * 0.15, right: coNumW * 0.05, bottom: coNumH * 0.12, left: coNumW * 0.12},
w = coNumW - margin.left - margin.right,
h = coNumH - margin.top - margin.bottom;
/* Axis info */
let x = d3.scaleTime().range([w, 0]),
y = d3.scaleBand().range([h, 0]),
xAxis = d3.axisBottom(x)
yAxis = d3.axisLeft(y),
dateFormat = d3.timeFormat("%Y-%m-%d %I:%M %p"),
weekdayFormat = d3.timeFormat("%w");
/* Filter data */
dataset.forEach(function(d, i) {
d.start_date = new Date(d.start_date);
d.end_date = new Date(d.end_date);
if (d.start_date >= new Date(start) && d.end_date <= new Date(current)) {
real.push(d);
}
});
/* X & Y domain rangs */
x.domain([new Date(start), new Date(current)]).range([0, w]);
y.domain(real.map(d => d.coNum)).padding(0.1);
/* Draw chart */
let realSvg = d3.select("body")
.append("svg")
.attr("width", coNumW)
.attr("height", coNumH)
.append("g").classed("no-select", true)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
realSvg.append("g")
.attr("class", "x_Axis")
.attr("transform", "translate(0, " + h + ")")
.call(xAxis)
realSvg.append("g")
.attr("class", "y_Axis")
.call(yAxis);
let tasksChange = realSvg.append("g")
.attr("class", "dataCont")
.selectAll("g")
.data(real)
.enter()
.append("g")
.on("mouseenter", showData);
/* Draw Rectangles */
tasksChange.append("rect")
.attr("x", function(d) {
return x(d.start_date) + 2; // + 2 is for padding
})
.attr("y", function(d) {
return y(d.coNum);
})
.attr("width", function(d) {
return x(d.end_date) - x(d.start_date) - 2;
})
.attr("height", function(d) {
return y.bandwidth();
});
/* Attempt to move x axis every second to the left (current time - 1 second) */
realSvg.select(".x.axis")
.transition()
.duration(1000)
.ease(d3.easeLinear)
.call(xAxis);
}
function showData(d) {
console.log("Start Date: " + dateFormat(d.start_date));
console.log("current Date: " + dateFormat(d.end_date));
console.log('CO: ', d.coNum)
console.log('************************* ')
}