Chartjs to animate x-axis - Javascript Chart.js

Javascript examples for Chart.js:Axis

Description

Chartjs to animate x-axis

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.bundle.js"></script> 
      <script type="text/javascript">
window.onload=function(){/*from   w  w w .j a va2 s. co m*/
   var canvas = document.getElementById('chart_canvas');
   var ctx = canvas.getContext('2d');
   var DATA_POINT_NUM = 10;
   var data = {
      labels: [],
      datasets: [
         {
            data: [],
         },
      ]
   }
   for (var i=0; i<DATA_POINT_NUM; i++) {
      data.datasets[0].data.push(Math.random()*10);
      data.labels.push(String.fromCharCode(65+i));
   }
   var oldDraw = Chart.controllers.line.prototype.draw;
   Chart.controllers.line.prototype.draw = function(animationFraction) {
      var animationConfig = this.chart.options.animation;
      if (animationConfig.xAxis === true) {
         var ctx = this.chart.chart.ctx;
         var hShift = (1-animationFraction)*ctx.canvas.width;
         ctx.save();
         ctx.setTransform(1, 0, 0, 1, hShift,0);
         if (animationConfig.yAxis === true) {
            oldDraw.call(this, animationFraction);
         } else {
            oldDraw.call(this, 1);
         }
         ctx.restore();
      } else if (animationConfig.yAxis === true) {
         oldDraw.call(this, animationFraction);
      } else {
         oldDraw.call(this, 1);
      }
   }
   var lineChart = new Chart(ctx, {
       type: 'line',
       data: data,
       options: {
          animation: {
             duration: 5000,
             xAxis: true,
             yAxis: true,
          }
       }
   });
    }

      </script> 
   </head> 
   <body>  
      <canvas id="chart_canvas"></canvas>   
   </body>
</html>

Related Tutorials