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

Chart.js 2.9.4柱状图tooltip异常:悬停第二列显示第一列内容

Angular 4 + Chart.js 2.9.4 柱状图Tooltip异常问题:悬停第二列显示第一列内容

在Angular 4项目中使用Chart.js 2.9.4实现柱状图与饼图时,遇到Tooltip异常:悬停第二列柱状图,却显示第一列的Tooltip内容。尝试调整Tooltip的position、mode等配置,甚至调试Chart.js 2.9.4库代码,仍未解决该问题。

异常截图:
Chart tooltip异常截图

相关代码

type: 'bar',
data: {
    labels: [X,Y,Z],
    datasets: [{
        label: [''],
        data: [
            10,
            12,
            14
        ],
        backgroundColor: [
            'red'
            'yellow',
            'blue'
        ],
        borderWidth: 1
    }]
},
options: {
    responsive: true,
    maintainAspectRatio: false,
    layout: {
        padding: {
            left: 0,
            right: 0,
            top: 0,
            bottom: 0
        }
    },
    scales: {
        yAxes: [
            {
                ticks: {
                    beginAtZero: true,
                    display: false,
                },
                gridLines: {
                    display: true,
                },
            },
        ],
        xAxes: [
            {
                gridLines: {
                    display: true,
                },
            },
        ],
    },
    legend: {
        display: false,
    },
    tooltips: {
        position: 'average',
        intersect: false,
        callbacks: {
            label: function (tooltipItem, data) {
                const dataset = data.datasets[tooltipItem.datasetIndex];
                const value = dataset.data[tooltipItem.index];
                const label = data.labels[tooltipItem.index];
                return `${label}: ${value}`;
            }
        }
    },
    onClick: function (event) {
        const activePoints = this.getElementsAtEventForMode(event, 'nearest', { intersect: true }, true);
        if (activePoints.length) {
            const firstPoint = activePoints[0];
            const label = this.chart.data.labels[firstPoint._index];
            const value = this.chart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
            console.log(`Clicked on ${label}: ${value}`);
        }
    }
}

问题根源与修复方案

你代码中的backgroundColor数组存在语法错误:'red'后面缺少逗号,导致数组实际解析为['redyellow', 'blue']——这意味着第三个柱子没有对应的颜色值,Chart.js内部处理时会因为数据长度不匹配引发索引错乱,最终导致Tooltip显示错误。

同时,label字段应该是字符串类型而非数组,虽然当前不直接引发问题,但可能带来其他潜在异常。

修复后的关键代码部分:

datasets: [{
    label: '', // 改为字符串而非数组
    data: [10,12,14],
    backgroundColor: [
        'red', // 补充缺失的逗号
        'yellow',
        'blue'
    ],
    borderWidth: 1
}]

将上述修改应用后,重新渲染图表,Tooltip应该能正常匹配对应柱子的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 14:52:18