Chartjs-Creating and Updating Graph in HTML and Javascript

3๐Ÿ‘

โœ…

If I understand correctly, then you are after something like this :

var myLineChart, c = 0, label = 0, randomnum, interval;

function renderchart() {
   var ctx = document.getElementById("bettingarea").getContext('2d');
   myLineChart = new Chart(ctx, {
      type: 'line',
      data: {
         labels: ["1", "2", "3", "4"],
         datasets: [{
            label: 'Crash Graph',
            data: [5.44, 5.67, 5.94, 6.12],
            backgroundColor: [
               'rgba(255, 99, 132, 0.2)',
               'rgba(54, 162, 235, 0.2)',
               'rgba(255, 206, 86, 0.2)',
               'rgba(75, 192, 192, 0.2)',
               'rgba(153, 102, 255, 0.2)',
               'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
               'rgba(255,99,132,1)',
               'rgba(54, 162, 235, 1)',
               'rgba(255, 206, 86, 1)',
               'rgba(75, 192, 192, 1)',
               'rgba(153, 102, 255, 1)',
               'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
         }]
      },
      options: {
         scales: {
            yAxes: [{
               ticks: {
                  beginAtZero: false
               }
            }]
         }
      }
   });
}

function updateChart(chart) {
   randomnum = Math.floor(Math.random() * (1000 - 100) + 100) / 100;
   chart.data.labels = [];
   chart.data.datasets[0].data = [];
   interval = setInterval(function() {
      if (c < randomnum) {
         c += 0.01;
         label++;
         //update chart
         chart.data.labels.push(label.toString());
         chart.data.datasets[0].data.push(+c.toFixed(2));
         chart.update();
      } else {
         clearInterval(interval);
         c = 0;
         label = 0;
         //updateChart(myLineChart) /* maybe call this function again */
      }
   }, 20);
}

window.onload = renderchart;
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="bettingarea"></canvas><br>
<button onclick="updateChart(myLineChart)">Update Chart</button>

correct me if I am wrong ๐Ÿ™‚

Leave a comment