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

Chart.js 浏览器缩放后工具提示定位异常及递归错误问题求助

Chart.js 浏览器缩放后工具提示定位异常及递归错误问题求助

我最近做了一个React项目,在仪表盘页面里用Chart.js实现了柱状图和饼图,原本一切功能都正常,但遇到了个让人头疼的问题——当浏览器缩放时,柱状图的工具提示显示不正常:鼠标移到柱子上时tooltip经常不弹出来,只有精准移到某个特定点才会触发显示。更糟的是,我尝试自定义tooltip的定位函数来修复这个问题时,还触发了递归错误。

有没有大佬能给我一些解决思路或建议?真的非常感谢!

以下是我当前的tooltip配置代码:

tooltip: {
    backgroundColor: "rgba(0, 0, 0, 0.7)",
    titleFont: {
        size: 12,
        weight: "bold",
    },
    bodyFont: {
        size: 10,
    },
    footerFont: {
        size: 8,
    },
    callbacks: {
        label: function (tooltipItem) {
            return ` ${tooltipItem.label}: ${tooltipItem.raw}`;
        },
    },
    position: function (context) {
        try {
            if (!context || !context.tooltip || !context.chart) {
                return { x: 0, y: 0 };
            }

            const { chart, tooltip } = context;

            // Ensure canvas exists before getting bounding box
            if (!chart.canvas) {
                return { x: 0, y: 0 };
            }

            // Get bounding rectangle of the chart canvas
            const canvasRect = chart.canvas.getBoundingClientRect();
            const zoomLevel = zoomLevelRef?.current || 1;

            // Prevent recursion by avoiding unnecessary updates
            const newX = (tooltip.caretX || 0) * zoomLevel + canvasRect.left;
            const newY = (tooltip.caretY || 0) * zoomLevel + canvasRect.top;

            if (Number.isNaN(newX) || Number.isNaN(newY)) {
                return { x: 0, y: 0 }; // Return safe fallback position
            }

            return { x: Math.round(newX), y: Math.round(newY) };
        } catch (error) {
            console.error("Tooltip positioning error:", error);
            return { x: 0, y: 0 }; // Fallback to prevent crash
        }
    },
},

备注:内容来源于stack exchange,提问作者Prince

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 19:58:00