echarts 自动滚动+ tooltip定时移动

4,047 阅读1分钟
  • 其实官网有写,侧面说明了 看文档的重要性。

开始之前先看一个 通过搜索得到的 echarts 自动滚动

  • 这是之前搜索到的,可以看出移动的逻辑是这样文章链接
    //通过定时器的方式刷新,改变statrValue,endValue
    setInterval(function () {
        // 每次向后滚动一个,最后一个从头开始。
        if (option.dataZoom[0].endValue == KSMC.length ) {
            option.dataZoom[0].endValue = 6; 
            option.dataZoom[0].startValue = 0;
        }
        else {
            option.dataZoom[0].endValue = option.dataZoom[0].endValue + 1;
            option.dataZoom[0].startValue = option.dataZoom[0].startValue + 1;
        }
        myChart.setOption(option);
    }, 2000);
    
    

再来看下官网文档

  • 文档直达地址
  • 上述可以看出文档是提供移动的方法的,原理是一样的 通过定时器移动元素,那么就有了下面的代码
  • this.mainLeftCarBox 是承载 echarts的元素
    // 定时器起始值
    let index = 0
    
    // 定时器
    let timer = setInterval(()=> {
      // 获取最大游标,用于重置定时器初始值
      let lendLength = option.xAxis.data.length
     
      // dataZoom
      this.mainLeftCarBox.dispatchAction({
        type: 'dataZoom',
        startValue: index, // 开始的位置
        endValue: 6 + index // 结束的位置
      });
    
      index++; // 下标自增
    
      // 重置下标
      if(index > lendLength) { index = 0 }
    
    }, 2000);
    
    // vue方法  页面销毁前 清除定时器
    this.$once('hook:beforeDestroy', ()=> { clearInterval(timer)})
    
  • 然后我们在创建一个 tooltip 的移动方法 他俩组合后是这样的 +
export const chartMotionAnimation = (opts) => {
   // chartDom 创建的chart元素
   // option 图表的配置
   // time 多久移动一次
   // self 用于组件销毁时清除定时器
  const { chartDom, option, time = 1500, self } = opts;

  // 定时器起始值
  let index = 0;

  // 获取最大游标,用于重置定时器初始值
  let lendLength = 0;
  const xData = option.xAxis;
  const seriesData = option.series;

  const type = Array.isArray(seriesData) ? seriesData[0].type : seriesData.type;

  if (['line', 'bar'].includes(type)) {
    lendLength = Array.isArray(xData) ? xData[0].data.length : xData.data.length;
  } else {
    lendLength = Array.isArray(seriesData) ? seriesData[0].data.length : seriesData.data.length;
  }

  // 定时器
  let timer = setInterval(() => {
    // tooltip
    chartDom.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: index,
      position: [10, 20]
    });

    // downplay
    let downplayIndex = index - 1;
    // 等于零时重置最后一个高亮元素
    if (index === 0) {
      downplayIndex = lendLength - 1;
    }
    chartDom.dispatchAction({
      type: 'downplay',
      seriesIndex: 0,
      dataIndex: downplayIndex,
      position: [10, 20]
    });

    // highlight
    chartDom.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      dataIndex: index,
      position: [10, 20]
    });

    // dataZoom
    chartDom.dispatchAction({
      type: 'dataZoom',
      startValue: index, // 开始的位置
      endValue: 6 + index // 结束的位置
    });

    index++; // 下标自增

    // 重置下标
    if (index >= lendLength) {
      index = 0;
    }
  }, time);

  // vue方法  页面销毁前 清除定时器
  self.$once('hook:beforeDestroy', () => {
    clearInterval(timer);
  });
};

结束