echarts 實現多圖聯動顯示tooltip


最近要實現echarts多圖聯動顯示tooltip,如下圖所示,當圖一中移動到某月份顯示tip,圖二中的相同月份要同步顯示tip。

主要實現的代碼如下:

 setTooltip() {
      const myChart1 = this.charts[0].myChart;
      const myChart2 = this.charts[1].myChart;
      myChart1.on('mousemove', (params) => {
        // 這里不直接用params.dataIndex是因為可能兩個圖表X軸的月份數據點不一致
        const dataIndex = this.charts[1].data.xAxis.findIndex(x => x === params.name);
        myChart2.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          // 我用的echarts版本是4.8.0,用name而不用dataIndex時,不知道為什么tooltip不顯示,所以這里用dataIndex
          // name: params.name
          dataIndex
        });
      })
    }

但是這里會有一個問題,就是僅當鼠標移動到圖一的標記點時,圖二才會同步顯示tip,如下圖:

這樣不是很方便,需要鼠標在圖表中其他位置移動時也觸發mousemove事件,具體代碼如下:

 setTooltip() {
      const myChart1 = this.charts[0].myChart;
      const myChart2 = this.charts[1].myChart;
      myChart1.getZr().on('mousemove', (params) => {
        const pointInPixel = [params.offsetX, params.offsetY];
        // 判斷當前鼠標移動的位置是否在圖表中
        if (myChart1.containPixel('grid', pointInPixel)) {
          //使用 convertFromPixel方法 轉換像素坐標值到邏輯坐標系上的點。獲取點擊位置對應的x軸數據的索引值
          const pointInGrid = myChart1.convertFromPixel({ seriesIndex: 0 }, pointInPixel);
          // x軸數據的索引值
          const xIndex = pointInGrid[0];
          // 使用getOption() 獲取圖表的option
          const op = myChart1.getOption();
          // 獲取當前點擊位置要的數據
          const xDate = op.xAxis[0].data[xIndex];
          // 這里不直接用params.dataIndex是因為可能兩個圖表X軸的月份數據點不一致
          const dataIndex = this.charts[1].data.xAxis.findIndex(x => x === xDate);
          myChart2.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            // 我用的echarts版本是4.8.0,用name而不用dataIndex時,不知道為什么tooltip不顯示,所以這里用dataIndex
            // name: params.name
            dataIndex
          });
        }
      })
  }

如下圖所示,即鼠標在圖表中移動時,即可觸發另外的圖表的showTip事件,而不僅僅通過移動到標記點觸發

參考博文:
在Echarts區域的任何位置精准觸發事件:https://https://www.shuzhiduo.com/A/obzbAV86dE/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM