Echarts 折线 实现 十字准星交互效果

160 阅读1分钟

echarts 实现以下图片上的交互

图片.png


import * as echarts from 'echarts';

var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;

option = {
  title: {
    text: 'Temperature Change in the Coming Week'
  },
  tooltip: {
    formatter: async (arg) => {
      // 这里需要异步处理以下,否则无法设置成功
      await setTimeout(function () {}, 0);
      myChart.setOption({
        series: [
          {
            markLine: {
              data: [
                {
                  yAxis: arg[0].value,
                  label: {
                    show: true
                  }
                }
              ]
            },
            symbolSize: (value, params) => {
              if (arg[0].dataIndex === params.dataIndex) {
                return 8;
              }
              return [0, 0];
            }
          }
        ]
      });
    }
  },
  legend: {},
  toolbox: {
    show: true,
    feature: {
      dataZoom: {
        yAxisIndex: 'none'
      },
      dataView: { readOnly: false },
      magicType: { type: ['line', 'bar'] },
      restore: {},
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    axisPointer: {
      show: true,
      snap: true,
      label: {
        show: true,
        backgroundColor: '#0000ff',
        color: '#fff'
      },
      lineStyle: {
        color: '#0000ff'
      }
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: '{value} °C'
    }
  },
  series: [
    {
      name: 'Highest',
      type: 'line',
      data: [10, 11, 13, 11, 12, 12, 9],
      symbol: 'emptyCircle',
      symbolSize: 0,
      markLine: {
        symbol: 'none',
        silent: true,
        data: [],
        label: {
          show: false,
          position: 'start',
          backgroundColor: '#0000ff',
          color: '#ffffff',
          padding: 2
        },
        lineStyle: {
          color: '#0000ff'
        },
        animation: false
      }
    },
    {
      name: 'Lowest',
      type: 'line',
      symbol: 'emptyCircle',
      symbolSize: 0,
      data: [1, -2, 2, 5, 3, 2, 0]
    }
  ]
};

option && myChart.setOption(option);