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

Chart.js环形图中心文本插件传入值运行时变为undefined问题求助

Chart.js环形图中心文本插件传入值运行时变为undefined问题求助

嘿,各位大佬,我最近在给Chart.js的环形图做中心文本插件时遇到了个棘手的问题,想请大家帮忙看看!

我想要实现的是在环形图的中心区域显示自定义文本,于是注册了一个名为doughnutInnerText的插件。如果在插件里硬编码文本值的话,一切都正常,但要是从图表配置的插件选项里传值,就出问题了——插件里前几次打印这个值都是正常的,但运行到某个阶段就突然变成undefined了,我加了非空判断也没起作用。

先给大家看看我的插件代码:

ChartJS.register({
  id: "doughnutInnerText",
  beforeDraw: (chart, args, options) => {
    const width = chart.width,
          height = chart.height,
          ctx = chart.ctx;
    ctx.restore();
    const fontSize = (height / 160).toFixed(2);
    ctx.font = fontSize + "em sans-serif";
    ctx.textBaseline = "top";

    // 硬编码值能正常显示,从配置传值的话前期有值,后期变成undefined
    const espnVal = chart.options.plugins.doughnutInnerText.myVal; 

    if (espnVal) {
      const textX = Math.round((width - ctx.measureText(espnVal).width) / 2),
            textY = height / 2.2;
      ctx.fillText(espnVal, textX, textY);
    }
    ctx.save();
  },
});

然后是我的图表配置代码(我试过去掉destroy(),但没改善):

const config = {
  type: "doughnut",
  data: data,
  options: {
    plugins: {
      doughnutInnerText: {
        espnVal: "My Text", // 这里传入的文本值
      },
      legend: {
        position: "top",
        labels: {
          font: {
            size: 66,
          },
        },
      },
    },
    animation: {
      onComplete: () => {
        const canvas = chart.canvas;
        const img = canvas.toDataURL("image/png", 1);
        this.modifyCardURL(this.state.adaptiveCard, img);
        // 拿到Base64后销毁图表
        chart.destroy();
      },
    },
  },
};

const ctx = document.createElement("canvas");
ctx.style.display = "none";
// 因为不渲染到页面,手动把canvas加入DOM
document.documentElement.appendChild(ctx);

const chart = new Chart(ctx, config as any);
chart.render();

特别奇怪的是,我在插件的beforeDraw里多次打印这个值,结果是这样的:

console.log(chart.options.plugins.doughnutInnerText.myVal) //"My Text"
console.log(chart.options.plugins.doughnutInnerText.myVal) //"My Text"
console.log(chart.options.plugins.doughnutInnerText.myVal) //"My Text"
console.log(chart.options.plugins.doughnutInnerText.myVal) //"undefined"

有没有大佬遇到过类似的情况?或者能帮我分析下为什么值会在运行时后期变成undefined吗?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 12:15:29