使用echarts柱状图模拟时间轴播放控制。开始/暂停/快进/慢进/点选
代码可直接放echart官方示例执行
let start = +new Date('2024-01-01');
let end = +new Date('2024-01-10');
let diff = end - start;
let dotLen = 200;
let data = [start, end];
option = {
color: ['#3398DB'],
tooltip: {
trigger: 'axis',
showContent: false,
axisPointer: {
type: 'line'
}
},
grid: {
top: '8%',
bottom: '90%'
},
xAxis: [
{
type: 'value',
axisLabel: {
formatter: (i) => {
return new Date(start + (i * diff) / dotLen).toLocaleDateString();
}
},
axisPointer: {
show: true
},
axisTick: {
inside: true
},
minorTick: {
show: true
},
splitLine: { show: false },
splitNumber: 10
}
],
yAxis: [
{
type: 'value',
show: false
}
],
series: [
{
name: 'x',
type: 'bar',
barWidth: '3',
animation: false
},
{
name: 'back',
type: 'bar',
barWidth: '5',
itemStyle: { color: 'rgba(0,0,0,0)' },
data: Array(dotLen)
.fill()
.map((it, i) => [i, 1]),
animation: false
}
]
};
let index = 0;
let btn = null;
let timerId = null;
let speed = 200;
const play = () =>
setInterval(() => {
const temp = index++ % dotLen;
myChart.setOption({
series: [
{
name: 'x',
data: Array(dotLen)
.fill()
.map((it, i) => {
return [i, i === temp];
})
}
]
});
}, speed);
const initControl = () => {
// 慢进
let slow = document.createElement('button');
slow.appendChild(document.createTextNode('slow'));
document.body.prepend(slow);
slow.onclick = () => {
if (timerId) {
speed = 1.1 * speed;
clearInterval(timerId);
timerId = play();
}
};
// 快进
let quick = document.createElement('button');
quick.appendChild(document.createTextNode('quick'));
document.body.prepend(quick);
quick.onclick = () => {
if (timerId) {
speed = 0.9 * speed;
clearInterval(timerId);
timerId = play();
}
};
// 播放/暂停
btn = document.createElement('button');
btn.appendChild(document.createTextNode('play'));
document.body.prepend(btn);
btn.onclick = () => {
if (timerId) {
btn.innerText = 'play';
clearInterval(timerId);
timerId = null;
} else {
btn.innerText = 'stop';
timerId = play();
}
};
};
initControl();
myChart.on('click', (evt) => {
if (timerId) btn.click();
index = evt.dataIndex;
myChart.setOption({
series: [
{
name: 'x',
data: Array(dotLen)
.fill()
.map((it, i) => {
return [i, i === index + 1];
})
}
]
});
index++;
});