Check Out the Chart.js Course: Chart.js, The Missing Manual Course
Categories
Uncategorized

Chart JS Doughnut Text Inside

Chart JS Doughnut Text Inside

To add text in the center of a doughnut chart requires a custom plugin. With a plugin we are able to create text or draw within the canvas. Once we created the plugin it still needs to be registered so Chart.js can recognize it.

Video Chart JS Doughnut text Inside

This video shows you how to create the in Chart.js text in the center of the doughnut chart. Secondly, it will also show how to connect it and register the plugin so Chart.js recognize it.

We will use the standard boiler template from the Chart.js getting started page.

Chart JS Doughnut text Inside

Snippets Chart JS Doughnut text Inside

This is the snippet used in the video for adding text in Chart.js doughnut text inside the center. It creates a custom plugin with the name doughnutLabels.

const doughnutLabel = {
  id: 'doughnutLabel',
  beforeDatasetsDraw(chart, args ,pluginOptions) {
    const { ctx, data } = chart;
    ctx.save(); 
    const xCoor = chart.getDatasetMeta(0).data[0].x;
    const yCoor = chart.getDatasetMeta(0).data[0].y;
    ctx.font = 'bold 30px sans-serif';
    ctx.fillStyle = 'rgba(54, 162, 235, 1)';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(`${data.labels[0]}: ${data.datasets[0].data[0]}`, xCoor, yCoor);
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish