chartjs 甜甜圈内的文本具有价值,但在运行时变得未定义

问题描述 投票:0回答:0

我有一个 chartjs 甜甜圈,我想在它的圆环/中间有文字。我已经为它创建/注册了一个插件。

如果我对值进行硬编码,它将起作用。如果我将圆环图中的值传递给插件,我可以看到插件具有该值,但在运行时的后期阶段变为未定义。我添加了条件,但没有任何效果。

我的插件;

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";
    const espnVal = chart.options.plugins.doughnutInnerText.myVal; //works if its hardcoded, otherwise will have a value but will become undefined later on

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

在 chartJS 图表本身的插件下,我有:

  doughnutInnerText: {
            espnVal: "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) //"My Text"
console.log(chart.options.plugins.doughnutInnerText.myVal) //"undefined"

我的完整 chartjs 代码(是的,已经尝试删除 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);
            //delete chart from DOM after we get the Base64 value
            chart.destroy();
          },
        },
      },
    };

    const ctx = document.createElement("canvas");
    ctx.style.display = "none";
    //since we are not rendering the chart, we have to manually add it to the DOM
    document.documentElement.appendChild(ctx);
    const chart = new Chart(ctx, config as any);
    chart.render();
  }
javascript reactjs typescript chart.js react-chartjs
© www.soinside.com 2019 - 2024. All rights reserved.