Chartjs animate x-axis fast - Javascript Chart.js

Javascript examples for Chart.js:Axis

Description

Chartjs animate x-axis fast

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(){//  w w w  .  ja v a  2 s . c o  m
   var canvas = document.getElementById('chart_canvas');
   var ctx = canvas.getContext('2d');
   var DATA_POINT_NUM = 58;
   var data = {
      labels: [],
      datasets: [
         {
            data: [],
         },
      ]
   }
   for (var i=0; i<DATA_POINT_NUM; i++) {
      data.datasets[0].data.push({    
             x: i,
             y: Math.random()*10
      });
      data.labels.push(String.fromCharCode(65+i));
   }
   function getXAxisLabel(value) {
      try {
         var xMin = lineChart.options.scales.xAxes[0].ticks.min;
      } catch(e) {
         var xMin = undefined;
      }
      if (xMin === value) {
         return '';
      } else {
         return data.labels[value];
      }
   }
   var lineChart = new Chart(ctx, {
       type: 'line',
       data: data,
       options: {
          animation: false,
          scales: {
             xAxes: [{
                type: 'linear',
                position: 'bottom',
                ticks: {
                   min: 0,
                   max: 10,
                   callback: getXAxisLabel, // function(value) { return data.labels[value]; },
                   autoSkip: false,
                   maxRotation: 0,
                },
             }]
          }
       }
   });
   var xMin = 0;  
   var xLength = 10;            
   var animationDuration = 5000;   
   var framesPerSec = 100;
   var frameTime = 1000/framesPerSec;
   var xStep = (DATA_POINT_NUM-xMin+xLength)/(animationDuration/1000*framesPerSec);
   function nextFrame() {
      var xMax = xMin+xLength;
      if (xMax < DATA_POINT_NUM-1) {
         if (xMax+xStep > DATA_POINT_NUM-1) {
            xMax = DATA_POINT_NUM-1;
            xMin = xMax-xLength;
         }
         lineChart.options.scales.xAxes[0].ticks.min = xMin;
         lineChart.options.scales.xAxes[0].ticks.max = xMax;
         lineChart.update();
         setTimeout(nextFrame, frameTime);
         xMin += 0.1;
      }
   }
   nextFrame();
    }

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

Related Tutorials