Reputation: 810
I'm currently working with Chart.js, and I need to change between two differents datasets. To do this I just change the dataset and use the Update function. The main problem is that when you change multiple times between the datasets, the animation dissapears and it looks horrible.
Here you can see what I'm talking about and my code. Does somebody know how could I fix it? Thanks a lot!
And here is my code, in case the link doesn't work:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Chart.js Example</title>
<!-- import plugin script -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js'></script>
</head>
<body>
<!-- bar chart canvas element -->
<canvas id="chart" width="600" height="400"></canvas>
<button onclick="manageCharts()" id="chartDataButton">Chart 2</button>
</body>
</html>
And the javascript code
Chart.defaults.global.responsive = false;
var chartData1 = {
labels : ["L1", "l2", "l3", "l4"],
datasets : [{
label: "LEGEND",
data : [13, 23, 9, 4],
backgroundColor: "#FF88CC",
borderColor: "#000000",
borderWidth: 1,
}]
}
var chartData2 = {
labels : ["L11", "L12"],
datasets : [{
label: '{{ legend }}',
data : [7, 1],
backgroundColor: "#FEFE65",
borderColor: "#00FFFF",
borderWidth: 2,
}]
}
var pieChartOptions = {
rotation: -Math.PI,
cutoutPercentage: 30,
circumference: Math.PI,
legend: {
position: 'left'
},
animation: {
animateRotate: true,
animateScale: false
}
};
// get chart canvas
var ctx = document.getElementById("chart").getContext("2d");
var pieChart = new Chart(ctx, {
type: 'pie',
data: chartData1,
options: pieChartOptions
});
function manageCharts(){
var button = document.getElementById("chartDataButton");
var previousData = pieChart.config.data;
if(previousData == chartData1){
button.textContent = "Chart 1";
showChart2Data();
}else if(previousData == chartData2){
button.textContent = "Chart 2";
showChart1Data();
}
}
function showChart2Data(){
pieChart.config.data = chartData2;
pieChart.update();
};
function showChart1Data(){
pieChart.config.data = chartData1;
pieChart.update();
};
Upvotes: 1
Views: 10821
Reputation: 647
I've updated your code in this jsfiddle to use the destroy()
function.
Using update()
doesn't seem reset the animation.
Using destroy()
removes the chart and then your code will recreate the new chart (and animation)
PS: Sorry for changing to jsfiddle from JS Bin. I was having troubles editing in JS Bin.
Upvotes: 1