Reputation: 1376
I have several Chart.js charts that I may need to update at a later time.
Is it possible to extract the myChart object from the canvas element at the time when I need to update the chart? Or do I have to save every myChart object in the global scope?
for(var i=1; i<=5; i++) {
createChart(i);
}
function createChart(i) {
var $chart = $('<canvas id="chart-' + i + '" width="400" height="400"></canvas>').appendTo('body');
var myChart = new Chart($chart, {
data: {
datasets: [{
data: [Math.random(), Math.random(), Math.random(), Math.random()]
}]
}
});
}
Now some pseudo-code how I would like to update say chart 2 at a later time:
var updateChart = $('#chart-2'); // This is where I'd need to get the chart data from the canvas element
updateChart.data.datasets[0].data = updateChart.data.datasets[0].data.push(Math.random());
updateChart.update();
Upvotes: 5
Views: 8852
Reputation: 157
ChartJS API actually offers the getChart
method to do what you want:
let chart = Chart.getChart('chart-2'); // Select by canvas ID
// OR
let canvas = document.querySelector('#chart-2')
let chart = Chart.getChart(canvas); // Select using the canvas element
// You can now update your chart
chart.data.datasets[0].data = newData;
chart.data.labels = newLabels;
chart.update();
Upvotes: 9
Reputation: 21
Chart.helpers.each(Chart.instances, function(instance){
console.log(instance);
});
Update: https://jsfiddle.net/furd1L27/14/
Upvotes: 2
Reputation: 1
I would recommend to store all data sent to chart in arrays. Once the array is updated you can send:
HTTP/AJAX/SOCKET.IO
indication to the client, and update the chart.
Upvotes: 0