Chartjs-Skipping the initial animation of a line chart

2👍

You can initially set the animation duration to 0 and then either:

  1. immediately set the animation duration, or
  2. specify the duration when calling the update() method.

Example:

let max = 10,
  min = -10,
  myChart = new Chart(document.getElementById('myChart'), {
    type: 'line',
    data: {
      labels: ['a', 'b', 'c'],
      datasets: [{
        label: 'series1',
        data: [5, 5, 5]
      }]
    },
    options: {
      maintainAspectRatio: false,
      scales: {
        yAxes: [{
          ticks: {
            max: 10,
            beginAtZero: true
          }
        }]
      },
      animation: {
        duration: 0
      }
    }
  });

// 1. immediately set the animation duration.
//myChart.config.options.animation.duration = 1000;

setInterval(function() {
  let a = getRandomInt(0, 3), // index to modify.
    b = getRandomInt(0, 11); // new value.
  myChart.config.data.datasets[0].data[a] = b;
  myChart.update(1000); // 2. specify the duration.
}, 2000); // update the chart every 2 seconds with a random value.

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart"></canvas>

Leave a comment