You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-chartjs-2自定义悬停线鼠标移出后不消失的解决方法

解决react-chartjs-2自定义悬停线移出不消失的问题

核心问题在于你的自定义插件只处理了鼠标悬停时的绘制逻辑,未监听鼠标移出图表区域的事件来清除悬停线。以下是修改后的完整实现:

修改后的自定义插件代码

const hoverLinePlugin = {
  id: 'hoverLine',
  afterInit(chart) {
    // 初始化存储悬停位置的变量
    chart.hoverPosition = null;
  },
  afterEvent(chart, event) {
    const { type } = event;
    
    // 鼠标移动时,判断是否在图表区域内并记录位置
    if (type === 'mousemove') {
      const { x, y } = event;
      const { left, right, top, bottom } = chart.chartArea;
      // 校验鼠标是否处于图表绘图范围内
      const isInChart = x >= left && x <= right && y >= top && y <= bottom;
      chart.hoverPosition = isInChart ? { x, y } : null;
      chart.update(); // 触发重绘更新状态
    } 
    // 鼠标移出图表时,清空悬停位置并触发重绘
    else if (type === 'mouseout') {
      chart.hoverPosition = null;
      chart.update();
    }
  },
  afterDraw(chart) {
    // 无悬停位置时直接跳过绘制
    if (!chart.hoverPosition) return;

    const ctx = chart.ctx;
    const { x, y } = chart.hoverPosition;
    const { left, right, top, bottom } = chart.chartArea;

    // 绘制垂直虚线
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(x, top);
    ctx.lineTo(x, bottom);
    ctx.strokeStyle = '#ccc';
    ctx.lineWidth = 1;
    ctx.setLineDash([5, 5]);
    ctx.stroke();
    ctx.restore();

    // 绘制水平虚线
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(left, y);
    ctx.lineTo(right, y);
    ctx.strokeStyle = '#ccc';
    ctx.lineWidth = 1;
    ctx.setLineDash([5, 5]);
    ctx.stroke();
    ctx.restore();
  }
};

关键修改点

  1. 新增mouseout事件处理:在鼠标移出图表时清空hoverPosition变量,并调用chart.update()触发重绘,让插件不再绘制悬停线。
  2. 增加图表区域校验:在mousemove事件中判断鼠标是否处于图表绘图范围内,避免鼠标在图表外部移动时误绘制悬停线。
  3. 绘制前置判断:在afterDraw阶段先检查hoverPosition是否存在,不存在则直接跳过绘制逻辑。

在React组件中使用插件

import { Line } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';

// 注册插件到Chart.js
Chart.register(...registerables, hoverLinePlugin);

function CustomChart() {
  const chartData = {
    // 你的图表数据
    labels: ['Jan', 'Feb', 'Mar', 'Apr'],
    datasets: [{
      label: 'Sample Data',
      data: [12, 19, 3, 5],
      borderColor: '#36A2EB',
      backgroundColor: '#9BD0F5'
    }]
  };

  const chartOptions = {
    // 你的图表配置
    responsive: true,
    plugins: {
      legend: { position: 'top' }
    }
  };

  return <Line data={chartData} options={chartOptions} />;
}

内容的提问来源于stack exchange,提问作者Digitalwolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 21:12:07