如何让echarts图表轮询高亮显示数据项

668 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第1天,点击查看活动详情

需求描述

可视化大屏中,为了更好的展示效果,需要让echarts图表在没有鼠标选中的情况下自动播放数据。效果下图所示。

chrome-capture-2022-2-31.gif

问题解决

Echarts中的事件分为两种,一种是鼠标事件,在鼠标点击某个图形上会触发,还有一种是调用dispatchAction后触发的事件。

Echarts中支持的图表行为,通过dispatchAction触发。

  • 高亮/取消高亮指定的数据图形, action类型为'highlight'/'downplay';通过指定系列index/id/name,数据项id/name高亮或取消高亮数据项。
  • 显示/隐藏提示框, action类型为'showTip'|'hideTip';通过指定系列index,数据项id/name,显示/隐藏提示框。 具体文档如下代码所示:
// 高亮/取消高亮指定数据图形
dispatchAction({ 
    // 高亮/取消高亮数据项
    type: 'highlight'|'downplay',
    // 用 index 或 id 或 name 来指定系列。
    // 可以使用数组指定多个系列。 
    seriesIndex?: number | number[], 
    seriesId?: string | string[], 
    seriesName?: string | string[], 
    // 数据项的 index,如果不指定也可以通过 name 属性根据名称指定数据项 
    dataIndex?: number | number[], 
    // 可选,数据项名称,在有 dataIndex 的时候忽略 
    name?: string | string[], 
});
// 显示/隐藏提示框
dispatchAction({ 
    // 显示/隐藏提示框
    type: 'showTip'|'hideTip',
    // 系列的 index,在 tooltip 的 trigger 为 axis 的时候可选。 
    seriesIndex?: number | number[],
    // 数据项的 index,如果不指定也可以通过 name 属性根据名称指定数据项 
    dataIndex?: number, 
    // 可选,数据项名称,在有 dataIndex 的时候忽略 
    name?: string,
    // 本次显示 tooltip 的位置。只在本次 action 中生效。 
    // 缺省则使用 option 中定义的 tooltip 位置。 
    position: number[] | string | Function,
});

代码实现

通过setInterval周期函数,每隔3s高亮下一个数据项,同时取消当前数据项的高亮效果。

autoShowTooltip = () => {
    let myChartPieIndex = 0;
    let dataCount = 8;
    setInterval(()=>{
      let instance = (this.refs.myEcharts as any).getEchartsInstance();
      instance.dispatchAction({
        type: 'downplay',
        seriesIndex: 0,
        dataIndex: (myChartPieIndex) % dataCount
      });
      instance.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: (myChartPieIndex+1) % dataCount
      })
      instance.dispatchAction({
        type: 'hideTip',
        seriesIndex: 0,
        dataIndex: (myChartPieIndex) % dataCount
      });
      instance.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: (myChartPieIndex+1) % dataCount
      });
      myChartPieIndex++
    }, 3000)
  }