echarts - click line trigger function getZr() - skill improvement

Today I saw the broken line chart being discussed in the technical group echarts. Some people encountered a function that clicks on the broken line to trigger a click event, but the clickclick event on the official website is only for the inflection point of the broken line.
insert image description here

But it was suggested that it can getZr()be achieved by the method

There is indeed a great god on the Internet who proposed the same solution, the link is as follows:

Echarts line chart clicks on the line area (including dots) to trigger an event: http://t.csdn.cn/eVstn

Paste the code below:

option = {
    
    
    tooltip: {
    
    
        trigger: 'axis'
    },
    legend: {
    
    
        data: ['邮件营销', '联盟广告']
    },
    xAxis: {
    
    
        type: 'category',
        boundaryGap: false,
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
    
    
        type: 'value'
    },
    series: [
        {
    
    
            name: '邮件营销',
            type: 'line',
            stack: '总量',
            data: [120, 132, 101, 134, 90, 230, 210]
        },
        {
    
    
            name: '联盟广告',
            type: 'line',
            stack: '总量',
            data: [220, 182, 191, 234, 290, 330, 310]
        },
    ]
};
myChart.getZr().on('click', function(params) {
    
    
  // 获取像素坐标点
  const pointInPixel = [params.offsetX, params.offsetY]
  const {
    
     target, topTarget } = params
  // 判断点击的点在  点击在折线的拐点 || 折线上
  if (target?.z === 2 || topTarget?.z === 2) {
    
    
  // 获取这条折线的 信息 也就是 index
  // 如果是拐点,直接读取 target.seriesIndex
  // 如果是折线上的点,读取 topTarget 对象下的继续寻找parent的信息的index
    const axs = target
      ? target.seriesIndex
      : topTarget.parent?.parent?.__ecComponentInfo?.index
    console.log(axs)
  }
})
// 将可以响应点击事件的范围内,鼠标样式设为pointer--------------------
myChart.getZr().on('mousemove', function(params) {
    
    
  const {
    
     topTarget } = params
  // 给折线的鼠标悬浮 变为 小手
  if (topTarget?.z === 2) {
    
    
    myChart.getZr().setCursorStyle('pointer')
  }
})

Record it first, and you can directly refer to it if you encounter the same problem in the future, complete! ! !

Guess you like

Origin blog.csdn.net/yehaocheng520/article/details/131432317