echarts--點(diǎn)擊圖表任意位置,獲取到該點(diǎn)的XY坐標(biāo)值

ec.png

代碼如下:(methods里)

  myChart =  this.$echarts.init(document.getElementById("myChart"))
    
    myChart.setOption(this.option)
    // 給整個(gè)畫布添加點(diǎn)擊事件
    myChart.getZr().on('click', function (param) {
      const pointInPixel = [param.offsetX, param.offsetY]
      console.log('pointInPixel', pointInPixel)
      // 使用 convertFromPixel方法 轉(zhuǎn)換像素坐標(biāo)值到邏輯坐標(biāo)系上的點(diǎn)。獲取點(diǎn)擊位置對應(yīng)的x軸數(shù)據(jù)的索引         值,借助于索引值的獲取到其它的信息
      // 轉(zhuǎn)換X軸坐標(biāo)
      let pointInGrid = myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel);
       // 轉(zhuǎn)換Y軸坐標(biāo)
       let pointInGrid2 = myChart.convertFromPixel({ seriesIndex: 1 }, pointInPixel);
      // x軸數(shù)據(jù)的索引值
      console.log('pointInGrid', pointInGrid2)
       // 所點(diǎn)擊點(diǎn)的X軸坐標(biāo)點(diǎn)所在X軸data的下標(biāo)
      let xIndex = pointInGrid[0];
       // 所點(diǎn)擊點(diǎn)的Y軸坐標(biāo)點(diǎn)數(shù)值
      let yIndex = pointInGrid2[1];
      // 使用getOption() 獲取圖表的option
      let op = myChart.getOption();
      //獲取到x軸的索引值和option之后,我們就可以獲取我們需要的任意數(shù)據(jù)。
      // 點(diǎn)擊點(diǎn)的X軸對應(yīng)坐標(biāo)的名稱
      var time = op.xAxis[0].data[xIndex];
      // 點(diǎn)擊點(diǎn)的series -- data對應(yīng)的值
      var value = op.series[0].data[xIndex];
      console.log('val', time)
    });

data中option內(nèi)容

  option:{
    tooltip:{
        show:true,
        trigger:"item"
    },
    legend:{
        show:true,
    },
    xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
        type: 'value',
        // data: [300, 600, 900, 1200, 1500, 1900],
        boundaryGap: [0, '30%']
    },
    series:[
        {
            name:"折線圖",
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line',
        },
        {
            name:"折線圖2",
            data: [620, 654, 500, 800, 900, 1000, 1100],
            type: 'line',
            itemStyle:{//隨機(jī)顏色
                color:"rgba("+ Math.floor(Math.random()*256) + ',' +  Math.floor(Math.random()*256) + ',' +Math.floor(Math.random()*256) + ',' +  (Math.random()*10).toFixed(1) +')'
            }
        }
    ]
  },
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容