Add title inside doughnut chart in Chartjs - Javascript Chart.js

Javascript examples for Chart.js:Doughnut Chart

Description

Add title inside doughnut chart in Chartjs

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://code.jquery.com/jquery-git.js"></script> 
      <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script> 
      <script type="text/javascript">
    $(window).on('load', function() {
var doughnutData = [/*w w  w . ja v a 2 s.co  m*/
  { value: 100, color:"#F7464A", highlight: "#FF5A5E", label: "Red" },
  { value: 50, color: "#CCCCCC", highlight: "#5AD3D1", label: "Green" }
];
var options = {
   showTooltips : true,
  animation: true,
  percentageInnerCutout : 70,
  onAnimationComplete: innerTextFunction
};
var chartCtx = $("#canvas").get(0).getContext("2d");
var textCtx = $("#text").get(0).getContext("2d");
var chart = new Chart(chartCtx).Doughnut(doughnutData, options);
function innerTextFunction() {
    var canvasWidthvar = $('#canvas').width();
    var canvasHeight = $('#canvas').height();
    var constant = 114;
    var fontsize = (canvasHeight/constant).toFixed(2);
    textCtx.font = fontsize + "em Verdana";
    textCtx.textBaseline="middle";
    var total = 0;
    $.each(doughnutData,function() {
      total += parseInt(this.value,10);
    });
    var tpercentage = ((doughnutData[0].value/total)*100).toFixed(2)+"%";
    var textWidth = textCtx.measureText(tpercentage).width;
    var txtPosx = Math.round((canvasWidthvar - textWidth)/2);
    textCtx.fillText(tpercentage, txtPosx, canvasHeight/4);
}
    });

      </script> 
   </head> 
   <body> 
      <div style="position: relative;"> 
         <canvas id="text" style="z-index: 1; position: absolute; left: 0px; top: 0px; width: 300px; height: 300px;"></canvas> 
         <canvas id="canvas" style="z-index: 2; position: absolute; left: 0px; top: 0px; width: 300px; height: 300px;"></canvas> 
      </div>  
   </body>
</html>

Related Tutorials