Adding a label to a doughnut chart in Chart.js - Javascript Chart.js

Javascript examples for Chart.js:Doughnut Chart

Description

Adding a label to a doughnut chart in Chart.js

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//from ww  w  .j  ava 2  s .c  o  m
function drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, midLabel, id) {
    var ctx = ctxElement;
    var data = {
        labels: ctxDataLabels,
        datasets: ctxDataSets
    };
    Chart.pluginService.register({
        afterDraw: function(chart) {
            if (chart.id != id) return;
            var width = chart.chart.width,
                height = chart.chart.height,
                ctx = chart.chart.ctx;
            ctx.restore();
            var fontSize = (height / 114).toFixed(2);
            ctx.font = fontSize;
            ctx.fillStyle = "black";
            ctx.textBaseline = "middle";
            var text = midLabel,
                textX = Math.round((width - ctx.measureText(text).width) / 2),
                textY = height / 2;
            ctx.fillText(text, textX, textY);
            ctx.save();
        }
    });
    var chart = new Chart(ctx, {
        type: ctxType,
        data: data,
        options: {
            legend: {
                display: false
            },
            responsive: true
        }
    });
};
drawChart(document.getElementById("canvas1"), "doughnut", [
    "Red",
    "Blue",
    "Yellow"
], [{
    data: [300, 50, 100],
    backgroundColor: [
        "#FF6283",
        "#36A2EB",
        "#FFCC54"
    ],
    hoverBackgroundColor: [
        "#FF6283",
        "#36A2EB",
        "#FFCC54"
    ]
}], "Canvas 1", 0);
drawChart(document.getElementById("canvas2"), "doughnut", [
    "Red",
    "Blue",
    "Yellow"
], [{
    data: [300, 50, 100],
    backgroundColor: [
        "#FF6283",
        "#36A2EB",
        "#FFCC54"
    ],
    hoverBackgroundColor: [
        "#FF6283",
        "#36A2EB",
        "#FFCC54"
    ]
}], "Canvas 2", 1);
drawChart(document.getElementById("canvas3"), "doughnut", [
    "Red",
    "Blue",
    "Yellow"
], [{
    data: [300, 50, 100],
    backgroundColor: [
        "#FF6283",
        "#36A2EB",
        "#FFCC54"
    ],
    hoverBackgroundColor: [
        "#FF6283",
        "#36A2EB",
        "#FFCC54"
    ]
}], "Canvas 3", 2);
    }

      </script> 
   </head> 
   <body> 
      <canvas id="canvas1"></canvas> 
      <canvas id="canvas2"></canvas> 
      <canvas id="canvas3"></canvas>  
   </body>
</html>

Related Tutorials