Generate randomly incrementing number over time for chartjs - Javascript Chart.js

Javascript examples for Chart.js:Chart Configuration

Description

Generate randomly incrementing number over time for 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/1.0.2/Chart.js"></script> 
      <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/seedrandom/2.4.0/seedrandom.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//  w  ww.  j a v  a 2 s  . co  m
   Counter = {
         time:Date.now(),
         count:0,
         rate:0.45
      };
   Counter.seed = function(seed, startTime)
   {
      this.time = startTime,
      this.count = 0,
      this.prng = new Math.seedrandom(seed);
      this.prng.getRandomInt = function(min, max) {
        return Math.floor(this() * (max - min)) + min;
      };
   };
   Counter.getNext = function(t){
      var diff = t - this.time;
      console.log(diff);
      if(diff <= 0) return this.count;
      this.time = t;
      var max = Math.ceil(diff/100 * this.rate);
      console.log("max: " + max);
      this.count += this.prng.getRandomInt(0,max);
      return this.count;
   };
   var results = [];
   var today = Date.now();
   Counter.seed("My Random Seed", today);
   for (var i = 0; i < 7; i++) {
      if(i === 4)
      {
         results.push(null);
      } else {
         var future = today +  86400000 * i;
         results.push(Counter.getNext(future));
      }
   }
   console.log(results);
      var data = {
       labels: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"],
       datasets: [
           {
               label: "My Second dataset",
               fillColor: "rgba(151,187,205,0.2)",
               strokeColor: "rgba(151,187,205,1)",
               pointColor: "rgba(151,187,205,1)",
               pointStrokeColor: "#fff",
               pointHighlightFill: "#fff",
               pointHighlightStroke: "rgba(151,187,205,1)",
               data: results
           }
       ]
   };
   var ctx = document.getElementById("myChart").getContext("2d");
   var myLineChart = new Chart(ctx).Line(data);
    }

      </script> 
   </head> 
   <body>  
      <canvas id="myChart" width="600" height="400"></canvas>   
   </body>
</html>

Related Tutorials