event handler on center of doughnut chart using chart.js - Javascript Chart.js

Javascript examples for Chart.js:Doughnut Chart

Description

event handler on center of doughnut chart using chart.js

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Doughnut chart click handler - Round empty div over canvas</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.js"></script> 
      <style id="compiled-css" type="text/css">

#chart, #myChart, .chart-text {  padding: 0; margin: 0; }
#chart { position: relative; }
.chart-text { position: absolute; border-radius: 100%; }


      </style> 
      <script type="text/javascript">
    window.onload=function(){/*  ww w  .j av a  2 s .  c om*/
var data = {
  labels: [
    "Red",
    "Blue",
    "Yellow"
  ],
  datasets: [
    {
      data: [300, 50, 100],
      backgroundColor: [
        "#FF6384",
        "#36A2EB",
        "#FFCE56"
      ],
      hoverBackgroundColor: [
        "#FF6384",
        "#36A2EB",
        "#FFCE56"
      ]
    }]
};
var promisedDeliveryChart = new Chart(document.getElementById('myChart'), {
  type: 'doughnut',
  data: data,
  options: {
     responsive: true,
    legend: {
      display: false
    }
  }
});
var text1 = document.getElementById('text1');
text1.addEventListener("click", function (e) {
  console.log("CLICKED!");
});
Chart.pluginService.register({
  beforeDraw: function(chart) {
    var width = chart.chart.width,
        height = chart.chart.height,
        ctx = chart.chart.ctx;
    ctx.restore();
    var fontSize = (height / 114).toFixed(2);
    ctx.font = fontSize + "em sans-serif";
    ctx.textBaseline = "middle";
    var text = "75%",
        m = ctx.measureText(text),
        textX = Math.round((width - m.width) / 2),
        textY = height / 2;
    var d = Math.min(width, height);
    var a = d / 2;
    text1.style.left = (((width - a) / 2 - 1)|0) + "px";
    text1.style.top = (((height - a) / 2 - 1)|0) + "px";
    text1.style.width = a + "px";
    text1.style.height = a + "px";
    ctx.fillText(text, textX, textY);
    ctx.save();
  }
});
    }

      </script> 
   </head> 
   <body> 
      <div id="chart"> 
         <canvas id="myChart"></canvas> 
         <div class="chart-text" id="text1"></div> 
      </div> 
      <hr> 
      <p>Event handler on center of doughnut chart</p> 
      <p>Round empty div over canvas</p> 
      <p>
         Code example for Stack Overflow answer: 
         <a href="https://stackoverflow.com/a/38432538/613198" target="_blank">https://stackoverflow.com/a/38432538/613198</a> 
      </p>  
   </body>
</html>

Related Tutorials