Echarts鼠标事件触发时如何获取当前位置对应的x轴、y轴实际数值
实现代码
你可以直接修改mousemove事件的逻辑如下:
quotesChart.getZr().on("mousemove", function(params){ const pointInPixel = [params.offsetX, params.offsetY]; // 先判断当前鼠标位置是否在grid区域内,避免无效取值 if (quotesChart.containPixel('grid', pointInPixel)) { const pointInGrid = quotesChart.convertFromPixel('grid', pointInPixel); // pointInGrid[0] 是类目轴对应的索引,取整后对应quotes数组下标 const xIndex = Math.round(pointInGrid[0]) const xAxisValue = quotes[xIndex]?.period; // pointInGrid[1] 就是y轴对应的实际数值,按需求保留小数位数即可 const yAxisValue = pointInGrid[1].toFixed(2); // 此处可直接使用拿到的两个值做后续业务处理 console.log('x轴值:', xAxisValue, 'y轴值:', yAxisValue); } })
逻辑说明
- 调用
containPixel方法先校验鼠标位置是否在图表坐标系范围内,避免鼠标移出图表区域时拿到无效值 - 你的x轴为
category类目类型,convertFromPixel返回的第一个值为类目的浮点下标,用Math.round取整后即可对应到quotes数组的索引,直接取对应项的period字段就是你需要的x轴实际值 - 返回的第二个值就是y轴对应的实际数值,可根据业务需要做格式化处理
内容的提问来源于stack exchange,提问作者user1519240
相关产品推荐
相关产品推荐

