echarts饼状图自动轮播高亮

echarts yekong 482℃

数据可视化大屏项目开发中,需要实现一个效果,饼状图每隔一段时间,饼状图的某个区域就会自动选中,类似鼠标移上去的效果,依次轮播显示数据。

echarts饼状图自动轮播高亮

实现代码

事先定义一个timer用来存放定时器,避免重复定时导致轮播异常,通过myChart.dispatchAction的downplay和highlight来实现饼状图的高亮。

myChart.dispatchAction({
type: 'downplay',
seriesIndex: 0,
dataIndex: currentIndex
});
let timer = null;
drawEcharts() {
  var that = this
  window.addEventListener('resize', this.drawEcharts)

  let myChart = echarts.init(this.$refs.echarts1)
  var colors = this.colorList
  var data = []
  that.list.forEach((type) => {
    if (type.checked) {
      var datas = {
        ...type,
        itemStyle: {
          normal: {
            borderColor: new echarts.graphic.LinearGradient(0, 0, 1, 1, [{
              offset: 0,
              color: type.color1
            }, {
              offset: 1,
              color: type.color2
            }]),
          }
        }
      }
      data.push(datas)
    }
  });
  var option = {
    color: colors,
    series: [
      {
        name: '市场快检',
        type: 'pie',
        roundCap: false,
        radius: ['68%', '78%'],
        center: ['50%', '50%'],
        borderCap: 'round',
        label: {
          show: false,
          normal: {
            show: false,
            fontSize: 14,
            color: '#92B2D7',
            position: 'center', // 在中心显示标签
            formatter: function (params) {
              return params.percent.toFixed(0) + '%'; // 显示百分比
            },
          },
          emphasis: {
            show: true,
            position: 'center', // 在中心显示标签
            formatter: function (params) {
              return params.percent.toFixed(0) + '%'; // 显示百分比
            },
            textStyle: {  // 这里添加自定义样式
              fontSize: 20,
              fontFamily: 'DIN-bold',
              fontWeight: 'bold',
              color: '#11FFFE'
            }
          },
        },

        labelLine: {
          show: false,
          length: 1,
          length2: 10
        },
        data: data
      }
    ]
  }
  myChart.clear()
  myChart.resize()
  myChart.setOption(option)
  let currentIndex = -1;  // 当前高亮的扇区的索引
  const dataLen = option.series[0].data.length; // 获取数据长度

  function autoHighlightPieSector() {
    // 如果存在前一个扇区,取消其高亮效果
    if (currentIndex !== -1) {
      myChart.dispatchAction({
        type: 'downplay',
        seriesIndex: 0,
        dataIndex: currentIndex
      });
    }

    // 递增索引
    currentIndex = (currentIndex + 1) % dataLen;

    // 高亮新的扇区
    myChart.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      dataIndex: currentIndex
    });
  }

// 每隔5秒自动高亮新的扇区
  function startAutoHighlight() {
    // 如果已经存在定时器,先清除
    if (timer) {
      clearInterval(timer);
    }

    // 创建新的定时器
    timer = setInterval(autoHighlightPieSector, 5000);
  }

  startAutoHighlight();
},
喜欢 (0)