Chartjs-Text in the middle of a doughnut for charjs

2👍

You shouldn’t use the chart dom element size but the chart area.

[{
  id: 'text',
  afterDatasetsDraw: function(chart) {
    const {ctx, chartArea} = chart; 
    const {left, top, width, height} = chartArea;
    ctx.save();
    var fontSize = (height / 50).toFixed(2); // In my opinion this should be reevaluated
    ctx.font = fontSize + "em sans-serif";
    ctx.textBaseline = "middle";
    ctx.fillStyle ="rgb(200,200,200)";
                
    var text = "'.$numVal.'",
      textX = Math.round((width - ctx.measureText(text).width) / 2),
      textY = height / 2;
                
    ctx.fillText(text, left + textX, top + textY);
    ctx.restore();
  }
}]

Leave a comment