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

ChartJS从2.7.2升级至4.4.1后自定义提示框与图例文本不显示

ChartJS 4.4.1 自定义提示框与图例文本修复方案

问题原因

ChartJS 3.x及以上版本对配置结构、插件API做了大幅重构,旧版2.7.2的tooltip和图例自定义逻辑不再兼容。以下是针对4.4.1版本的适配代码及改动说明:

修复后完整代码

new Chart(document.getElementById('donutChart'), {
  type: 'doughnut',
  data: {
    labels: ['Red', 'Blue', 'Green', 'Teal', 'Yellow'],
    datasets: [{
      data: [123, 321, 213, 111, 222],
      backgroundColor: ['Red', 'Blue', 'Green', 'Teal', 'Yellow'],
      hoverOffset: 4
    }]
  },
  options: {
    plugins: {
      datalabels: {
        color: 'white',
        font: {
          weight: 'bold'
        },
      },
      // 提示框配置(新版移至plugins.tooltip下)
      tooltip: {
        backgroundColor: '#FFF',
        displayColors: false,
        title: {
          color: 'black',
          font: {
            size: 14
          }
        },
        body: {
          color: '#000',
          font: {
            size: 14
          }
        },
        callbacks: {
          // 新版回调参数为context对象
          title: function(context) {
            const index = context[0].dataIndex;
            return context[0].chart.data.labels[index];
          },
          label: function(context) {
            return context.parsed;
          },
          afterLabel: function(context) {
            const dataset = context.chart.data.datasets[0];
            const total = dataset.data.reduce((a, b) => a + b, 0);
            const percent = Math.round((context.parsed / total) * 100);
            return `(${percent}%)`;
          }
        }
      },
      // 图例配置(新版用generateLabels自定义文本)
      legend: {
        position: 'bottom',
        labels: {
          generateLabels: function(chart) {
            const dataset = chart.data.datasets[0];
            const total = dataset.data.reduce((a, b) => a + b, 0);
            return chart.data.labels.map((label, index) => {
              const value = dataset.data[index];
              const percent = Math.round((value / total) * 100);
              return {
                text: `${value} | ${label} | ${percent}%`,
                fillStyle: dataset.backgroundColor[index],
                strokeStyle: dataset.backgroundColor[index],
                index: index
              };
            });
          }
        }
      }
    },
    maintainAspectRatio: false
  }
});

关键改动说明

  • 提示框(Tooltip)适配:

    • 旧版options.tooltips迁移至options.plugins.tooltip,调整配置层级
    • 回调函数参数从tooltipItem, data改为context对象,需通过context.dataIndex、context.parsed等属性获取数据
    • 字体、颜色等样式属性从扁平化命名(如titleFontSize)改为嵌套结构(如title.font.size)
  • 图例文本自定义:

    • 移除旧版通过afterLayout插件修改legendItems的逻辑,改用plugins.legend.labels.generateLabels回调直接生成自定义图例项
    • 在generateLabels中计算数据总值,为每个标签拼接数值、名称、百分比,确保渲染时直接使用修改后的文本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:55:18