返回 导航

其他

hangge.com

ECharts - 实现鼠标移到数据点附近时就触发tooltip提示框显示功能

作者:hangge | 2025-02-10 09:00

1,需求说明

(1)我们知道使用 ECharts 绘制折线图时,通过 tooltip 配置属性,可以实现鼠标移动到数据点上时显示相应的 tooltip 提示框。

(2)这个功能必须鼠标指针准确移动到数据点上才触发,但有时点比较小用起来并不是很方便。因此,我们希望增加一些容错区域,即鼠标移动到数据点附近时(比如 10 像素内)即显示该数据点的 tooltip 提示框。

2,功能实现

(1)下面是实现该需要的样例代码,具体逻辑如下:
  • 监听鼠标事件,获取鼠标在图表区域中的位置。
  • 使用 chart.convertToPixel 将所有数据点的坐标转换为像素坐标。 
  • 计算鼠标与每一个数据点的距离,判断距离是否小于某个阈值(如 10 像素),从而决定是否显示 tooltip
  • 最后,通过 dispatchAction 手动触发显示、隐藏 tooltip 以及高亮点显示取消操作。
<template>
  <div id="chart" ref="chart" style="width: 600px; height: 400px;"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      const chart = echarts.init(this.$refs.chart);

      const option = {
        tooltip: {
          trigger: "item", // 设置为 'item' 触发方式
          axisPointer: {
            type: "none", // 禁用默认的 axisPointer
          },
        },
        xAxis: {
          type: "category",
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "访问量",
            type: "line",
            symbol: "circle", // 数据点显示为圆形
            symbolSize: 8, // 数据点大小
            data: [120, 132, 101, 134, 90, 230, 210],
          },
        ],
      };

      chart.setOption(option);

      // 鼠标移动事件监听
      chart.getZr().on("mousemove", (params) => {
        const pointInPixel = [params.offsetX, params.offsetY];
        
        // 遍历数据点,计算鼠标与每个点的距离
        let nearestDataIndex = -1;
        let minDistance = Infinity; // 初始化最小距离

        option.series[0].data.forEach((value, index) => {
          const pixel = chart.convertToPixel({ seriesIndex: 0 }, [index, value]);
          const distance = Math.sqrt(
            Math.pow(pixel[0] - pointInPixel[0], 2) + Math.pow(pixel[1] - pointInPixel[1], 2)
          );

          if (distance < minDistance && distance <= 10) { // 10 像素为触发范围
            minDistance = distance;
            nearestDataIndex = index;
          }
        });
        if (nearestDataIndex !== -1 ) {
           // 高亮当前点并显示 tooltip
           chart.dispatchAction({
            type: "highlight",
            seriesIndex: 0,
            dataIndex: nearestDataIndex,
          });
          chart.dispatchAction({
            type: "showTip",
            seriesIndex: 0,
            dataIndex: nearestDataIndex,
          });
        } else {
          // 鼠标离开所有数据点时,取消高亮点和提示框
          chart.dispatchAction({
            type: "downplay",
            seriesIndex: 0
          });
          chart.dispatchAction({
            type: "hideTip",
          });
        }
      });
    },
  },
};
</script>

(2)运行效果如下,可以看到当我们鼠标指针在某个数据点附近时,就能触发该数据点 tooltip 的显示。
评论

全部评论(0)

回到顶部