需求: echart 直方图的数据自动滚动(类似直播间发言那种)
思路: 修改option
里面的dataZoom
的endValue
和startValue
dataZoom 配置项
- startValue:数据窗口范围的起始数值。
- endValue:数据窗口范围的结束数值。
- yAxisIndex:设置 dataZoom-inside 组件控制的 y轴
做法
<div class="chart" id="testChart" onmouseover="cleartestInterval()" onmouseleave="setTestInterval()"></div>
let testChart, testOption, testInterval; // 测试
// 初始化图表
function initTestChart() {
testChart = echarts.init(document.getElementById("testChart"));
testOption = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
yAxis: [
{
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
axisTick: {
alignWithLabel: true
}
}
],
xAxis: [
{
type: 'value'
}
],
dataZoom: [{
type: 'inside',
yAxisIndex: [0],
startValue: 0,
endValue: 2
}],
series: [
{
name: 'Direct',
type: 'bar',
barWidth: '60%',
data: [10, 52, 200, 334, 390, 330, 220]
}
]
};
testOption && testChart.setOption(testOption);
}
// 清除定时器
function cleartestInterval() {
cleartestInterval(testInterval);
}
// 设置定时器
function setTestInterval() {
testInterval = setInterval(function() {
if(testOption.dataZoom[0].endValue===6) { // 滚动到最后一个数据,回到起始位置
testOption.dataZoom[0].startValue = 0;
testOption.dataZoom[0].endValue = 2;
} else {
testOption.dataZoom[0].startValue++;
testOption.dataZoom[0].endValue++;
}
testChart.setOption(testOption);
}, 3000)
}