- 在echart圖表中,經常需要獲取當前鼠標所在點的值,一般情況下都會通過
let chartInstance = echart.init(dom);
chartInstance.off('showTip');//這裏是爲了防止多次註冊事件
chartInstance.on('showTip',function(param)
{
let nowDataIndex = param.dataIndex;
);
來獲取當前點的數據索引,然後通過原始數據獲取當前鼠標所在點的數據;
- 然而,這樣的獲取方法有個缺點,僅能獲取到當前鼠標所在的位置最近的點的數據,並不能獲取任意位置的x軸數值和y數值
- 像這樣,我們僅能獲取到這個
點A
和點B
的值,當鼠標在AB之間時,無法準確獲取X軸位置 - 我原先的做法是這樣的:
//一下時showTip的回調函數中的內容
let x = param.x;
let nowWidth = chartInstance.getWidth();
if(nowWidth <=0)
{
return;
}
let rate = (x-gridLeft)/nowWidth; //gridLeft是 option中的grid中設置的left的像素值
//依據當前像素偏移的比例,以X軸的最大最小值作爲基準,結合當前軸的縮放比例,獲取當前位置的X軸的值
let nowXData = self.getDataByRate(rate);
- 可惜的是,這樣的做法算出來的數據不夠準確,因爲echart本身數軸縮放,數據採樣等問題,這樣按比例獲取的數據的精確度不夠
經過一番查找,發現echart 4
中,增加了一個用於像素座標轉換到echart邏輯座標的API,有了這個,自然就能精確的獲取當前鼠標所在位置的X值和Y值了
echartsInstance.convertFromPixel Function
(
// finder 用於指示『使用哪個座標系進行轉換』。
// 通常地,可以使用 index 或者 id 或者 name 來定位。
finder: {
seriesIndex?: number,
seriesId?: string,
seriesName?: string,
geoIndex?: number,
geoId?: string,
geoName?: string,
xAxisIndex?: number,
xAxisId?: string,
xAxisName?: string,
yAxisIndex?: number,
yAxisId?: string,
yAxisName?: string,
gridIndex?: number,
gridId?: string
gridName?: string
},
// 要被轉換的值,爲像素座標值,以 echarts 實例的 dom 節點的左上角爲座標 [0, 0] 點。
value: Array|string
// 轉換的結果,爲邏輯座標值。
) => Array|string
轉換像素座標值到邏輯座標系上的點
- 下面是我使用的解決方案:
let x = param.x; //當前點相對於echart dom的左上角的像素偏移
let y = param.y;
let result = self.chartInstance.convertFromPixel({
seriesIndex:0,
xAxisIndex:0
},[x,y]);
//這個result就是我們需要的 【x,y】數據了