Chartjs Extend

Extending chartjs for adding text at center.

by Debasis Panda

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.js"></script>
<canvas id="chart-area"></canvas>

JavaScript

// **** Extending Doughnut Chart **** //

Chart.defaults.derivedDoughnut = Chart.defaults.doughnut;
var customDoughnut = Chart.controllers.doughnut.extend({
  draw: function(ease) {
    Chart.controllers.doughnut.prototype.draw.apply(this, [ease]);
    var width = this.chart.chart.width,
      height = this.chart.chart.height,
      titleHeight = this.chart.titleBlock.height,
      legendHeight = this.chart.legend.height;
    var total = this.getMeta().total;
    var fontSize = (height / 114).toFixed(2);
    var ctx = this.chart.chart.ctx;
    ctx.font = fontSize + "em Verdana";
    ctx.textBaseline = "middle";
    var text = total,
      textX = Math.round((width - ctx.measureText(text).width) / 2),
      textY = (height+titleHeight+legendHeight)  / 2;

    ctx.fillText(text, textX, textY);
  }
});
Chart.controllers.derivedDoughnut = customDoughnut;

// **** Extending Doughnut Chart **** //
// ************* End ************* //


var randomScalingFactor = function() {
  return Math.round(Math.random() * 100);
};
var chartColors = {
	red: 'rgb(255, 99, 132)',
	orange: 'rgb(255, 159, 64)',
	yellow: 'rgb(255, 205, 86)',
	green: 'rgb(75, 192, 192)',
	blue: 'rgb(54, 162, 235)',
	purple: 'rgb(153, 102, 255)',
	grey: 'rgb(201, 203, 207)'
};
var config = {
  type: 'derivedDoughnut',
  data: {
    datasets: [{
      data: [
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor(),
      ],
      backgroundColor: [
        chartColors.red,
        chartColors.orange,
        chartColors.yellow,
        chartColors.green,
        chartColors.blue,
      ],
      label: 'Dataset 1'
    }],
    labels: [
      "Red",
      "Orange",
      "Yellow",
      "Green",
      "Blue"
    ]
  },
  options: {
    responsive: true,
    legend: {
      position: 'top',
    },
    title: {
      display: true,
      text: 'Chart.js Doughnut Chart Extended'
    },
    animation: {
     ...