Click pie chart to show its color in chartjs - Javascript Chart.js

Javascript examples for Chart.js:Pie Chart

Description

Click pie chart to show its color 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://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.min.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){// w  w  w  .j  ava2  s  .c  o m
var clickedArea = "";
var canvas = document.getElementById("ctx");
var ctx = canvas.getContext("2d");
var donut = new Chart(ctx, {
   type: 'doughnut',
   data: {
      labels: [
         "Red","Green","Blue","Orange","Purple"
         ],
      datasets: [{
         backgroundColor: [
            "#f00","#0f0","#00f","#f40","#f0f"
         ],
         data: [
            40,52,65,35,16
         ]
      }]
   },
   options: {
         segmentShowStroke : false,
         segmentStrokeColor : "#fff",
         segmentStrokeWidth : 2,
         cutoutPercentage : 70,
         animationSteps : 100,
         animationEasing : "easeOutBounce",
         animateRotate : false,
         animateScale : false,
         responsive: false,
         maintainAspectRatio: true,
         showScale: true,
         animateScale: true,
         legend: { display: false },
         tooltips: {
            enabled: false
         },
      onClick(evt) {
        var activePoints = donut.getElementsAtEvent(evt);
        var chartData = activePoints[0]['_chart'].config.data;
        var idx = activePoints[0]['_index'];
        var label = chartData.labels[idx].toUpperCase();
        this.selected = label;
          this.update();
      }
      },
    plugins: [{
      afterDraw(chart, easing) {
        ctx.font = "bold 18px Verdana, Arial, sans-serif";
        var textWidth = ctx.measureText(chart.selected).width;
        ctx.fillStyle = "#000";
        ctx.fillText(chart.selected || '', (250/2) - (textWidth/2), (250/2));
      }
    }]
   });
    }

      </script> 
   </head> 
   <body> 
      <canvas id="ctx" width="250" height="250"></canvas>  
   </body>
</html>

Related Tutorials