Chartjs-Text inside a chartjs doughnut has value but becomes undefined in runtime

0๐Ÿ‘

โœ…

2 thins, you configure your plugin to listen to the value myVal while you configure it in your options as espnVal so you need to read that. Also it is better practice to use the options object since it is the object of your plugin options so you dont need to drill through the entire chart path.

With that you will get this:

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.2.1"></script>
<canvas id="myChart"></canvas>
<style>
  #myChart {
    width: 400px;
    height: 400px;
  }
</style>
<script>
  Chart.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 = options.espnVal; //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();
    },
  });

  const data = {
    labels: ["hello", "world", "!"],
    datasets: [{
      data: [2, 5, 6]
    }]
  };

  // Chart options
  const options = {
    plugins: {
      doughnutInnerText: {
        espnVal: "My Text",
      }
    }
  };

  // Create the chart
  var ctx = document.getElementById('myChart').getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: data,
    options: options
  });
</script>

Leave a comment