Chart.js set active segment on initialize - Javascript Chart.js

Javascript examples for Chart.js:Chart Configuration

Description

Chart.js set active segment on initialize

Demo Code

ResultView the demo in separate window

<html lang="en">
   <head> 
      <title>Chart.js Setting a Segments Hover Style</title> 
   </head> 
   <body translate="no"> 
      <div id="canvas-holder" style="width:40%"> 
         <h1>
            Setting Segment Hover Style in 
            <span id="timer">5 seconds</span>
         </h1>
         <h1> 
            <canvas id="chart-area"></canvas> 
         </h1>
      </div> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> 
      <script>
      window.chartColors = {/* ww w .  j av a 2s  .c om*/
   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(231,233,237)'
};
var randomScalingFactor = function() {
  return Math.round(Math.random() * 100);
};
var ctx = document.getElementById("chart-area").getContext("2d");
var myPie = new Chart(ctx, {
  type: 'pie',
  data: {
    datasets: [{
      data: [
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor(),
      ],
      backgroundColor: [
        window.chartColors.red,
        window.chartColors.orange,
        window.chartColors.yellow,
        window.chartColors.green,
        window.chartColors.blue,
      ],
      label: 'Dataset 1'
    }],
    labels: [
      "Red",
      "Orange",
      "Yellow",
      "Green",
      "Blue"
    ]
  },
  options: {
    responsive: true
  }
});
var segmentIndexToHihlight = 0;
var timerDuration = 3;
var timer = setInterval(function() {
  timerDuration--;
  $('#timer').text(timerDuration + ' seconds');
}, 1000);
setTimeout(function() {
  var activeSegment = myPie.data.datasets[0]._meta[0].data[segmentIndexToHihlight];
  myPie.updateHoverStyle([activeSegment], null, true);
  myPie.render();
  $('#timer').text('(already set)');
  clearInterval(timer);
}, timerDuration * 1000);
      </script>  
   </body>
</html>

Related Tutorials