2👍
Well, that is not a correct way to destroy chart, the chart variable is a local variable and you are creating a new chart to the local variable and destroying that again that doesn’t mean it has destroyed all other previously created instances. One of the solutions would create a global variable to hold charts and destroy if everytime when the genCharts() is called. Here is the fiddle -> http://jsfiddle.net/srgw2y7m/
Hope it helps!
var chart;
function genCharts() {
if (chart) {
chart.destroy();
}
var colours = ['#ff3232', '#ff5731', '#ff9130', '#ffc730', '#fffb30', '#cbff30', '#7bff30', '#30ff55', '#30ffb9', '#30f4ff', '#42a3ff', '#6083ff', '#7760ff', '#c535ff', '#ff34fb', '#ff33aa', '#ff3276', '#ff3149', '#ff3232', '#ff5731', '#ff9130', '#ffc730', '#fffb30', '#cbff30', '#7bff30', '#30ff55', '#30ffb9', '#30f4ff', '#42a3ff', '#6083ff', '#7760ff', '#c535ff', '#ff34fb', '#ff33aa', '#ff3276', '#ff3149', '#ff3232', '#ff5731', '#ff9130', '#ffc730', '#fffb30', '#cbff30', '#7bff30', '#30ff55', '#30ffb9', '#30f4ff', '#42a3ff', '#6083ff', '#7760ff', '#c535ff', '#ff34fb', '#ff33aa', '#ff3276', '#ff3149']
var chartTheme = {
type: 'line',
data: {
labels: ['3.1', '3.2'],
},
options: {
legend: {
display: false
},
tooltips: {
xPadding: 15,
yPadding: 15,
titleFontColor: 'rgb(256,256,256)',
backgroundColor: 'rgba(67, 183, 249,0.8)',
displayColors: false,
cornerRadius: 3,
},
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'PRICE'
}
}]
}
},
};
var chartId = document.getElementById('chart').getContext('2d');
chart = new Chart(chartId, chartTheme);
var array = [Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random()];
var array2 = [Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random()];
var i;
for (i = 0; i < array.length; i++) {
var newData = {
data: [array[i], array2[i]],
label: 'random number',
pointStyle: 'rectRot',
pointRadius: 5,
pointBorderWidth: 5,
pointHoverBorderColor: 'rgba(256,256,256)',
pointHoverRadius: 8,
pointHoverBorderWidth: 8,
borderColor: colours[i]
}
chart.data.datasets.push(newData);
}
chart.update();
}
0👍
You are using the .destroy()
method correctly. When I encountered the same issue as you I ended up following other people’s recommendation and destroying the entire canvas
element from the DOM and re-rendering it.
I would alter your genCharts()
function to look like this:
$('#chart').remove();
$('#canvasContainer').append("<canvas width='10' height='10' id='chart' style='height:10px; width: 100px;'></canvas>");
var chartId = document.getElementById('chart').getContext('2d');
var chart = new Chart(chartId, chartTheme);
If you can figure out how to get .destroy()
working correctly let me know! I would love to do it that way as well but couldn’t figure it out for the life of me.
Fiddle here: https://jsfiddle.net/Lmp52046/1/