[Chartjs]-ChartJS replay chart animation when called by show()

2👍

From this answer and from the lack of options available in the Docs, it looks like the only feasible options would be these hacks:

  • redraw the chart with JS using new Chart or
  • change some minor configuration, or recreate an instance of the chart data and then call the update() method.

e.g.: Call the data through a function, and when you want the animation to happen, call the same function again. Because it now has a new array (even though it’s the same data), the chart re-animates.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

	<button onclick="updateChart()">Update</button>
    <canvas id="myChart"></canvas>
    <script>
    
        var ctx = document.getElementById('myChart').getContext('2d');
		
		var chartData = {
			type: 'line',
			data: {
				labels: ["January", "February", "March", "April", "May", "June", "July"],
				datasets: createDataset()
			}
        };
        var chart = new Chart(ctx, chartData);
		
		function updateChart(){
			chartData.data.datasets = createDataset()
			chart.update();
		}
		
		function createDataset(){
			return [{
                label: "My First dataset",
                backgroundColor: 'rgb(255, 99, 132)',
                borderColor: 'rgb(255, 99, 132)',
                data: [0, 10, 5, 2, 20, 30, 45],
				fill: false
            }];
		}
    //ignore next line, it's to deal with a bug from chartjs cdn on stackoverflow
    console.clear();
    </script>

Leave a comment