在ECharts中如何通過getZr().on(‘click’)獲取餅圖的具體數據?

在ECharts中如何通過getZr().on(‘click’)獲取餅圖的具體數據?

echarts餅圖點擊事件:精準獲取數據詳解

在ECharts中,使用getZr().on(‘click’)監聽餅圖點擊事件時,直接獲取數據并非易事。本文將詳細講解如何利用getZr().on(‘click’)結合其他方法,準確獲取餅圖點擊區域對應的數據,并解決myChart.containPixel()方法的使用問題。

getZr().on(‘click’)返回的是ECharts的渲染層ZRender的點擊事件。點擊餅圖時,target屬性為PiePiece,但這并不直接包含數據信息。我們需要進一步處理才能獲取對應的數據項。

關鍵在于結合myChart.containPixel()和myChart.convertFromPixel()方法。myChart.containPixel()用于判斷點擊位置是否在圖表區域內;myChart.convertFromPixel()則將像素坐標轉換為圖表坐標,從而找到對應的數據點。

以下代碼示例演示了如何獲取單環餅圖的數據:

myChart.getZr().on('click', function(params) {     const pointInPixel = [params.offsetX, params.offsetY];     if (myChart.containPixel('global', pointInPixel)) {         const pointInGrid = myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel);         const dataIndex = myChart.getModel().getSeriesByIndex(0).getData().indexOfNearest('value', pointInGrid);         const data = myChart.getModel().getSeriesByIndex(0).getData().getRawDataItem(dataIndex);         console.log(data); // 獲取到具體的數據     } });

代碼首先獲取點擊事件的像素坐標,然后使用myChart.containPixel()判斷點擊是否在圖表范圍內。如果在范圍內,則將像素坐標轉換為圖表坐標,并使用indexOfNearest()找到最接近點擊位置的數據項索引,最后通過getRawDataItem()獲取該數據項的原始數據。

對于多環餅圖,需要根據環形索引(seriesIndex)分別獲取數據:

myChart.getZr().on('click', function(params) {     // ... (像素坐標判斷同單環餅圖) ...     for (let i = 0; i < myChart.getModel().getSeries().length; i++) {         const pointInGrid = myChart.convertFromPixel({ seriesIndex: i }, pointInPixel);         const dataIndex = myChart.getModel().getSeriesByIndex(i).getData().indexOfNearest('value', pointInGrid);         const data = myChart.getModel().getSeriesByIndex(i).getData().getRawDataItem(dataIndex);         console.log(`環形 ${i+1} 數據:`, data);     } });

此代碼循環遍歷每個環形,分別進行坐標轉換和數據查找,從而獲取每個環形的數據。

通過以上方法,您可以高效準確地從ECharts餅圖點擊事件中獲取所需數據,實現更豐富的交互功能。 記住seriesIndex參數在多環餅圖中至關重要。

? 版權聲明
THE END
喜歡就支持一下吧
點贊13 分享