英文:
Chart.js: get chart data from canvas
问题
我有几个可能需要在以后更新的 Chart.js 图表。
在需要更新图表时,是否可以从画布元素中提取 myChart 对象?或者我必须在全局范围内保存每个 myChart 对象?
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()]
}]
}
});
}
现在是一些伪代码,说明我如何在以后更新第二个图表:
```javascript
var updateChart = $('#chart-2'); // 这是我需要从画布元素中获取图表数据的地方
updateChart.data.datasets[0].data.push(Math.random());
updateChart.update();
英文:
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();
答案1
得分: 1
Chart.helpers.each(Chart.instances, function(instance){
console.log(instance);
});
Update:
https://jsfiddle.net/furd1L27/14/
英文:
Chart.helpers.each(Chart.instances, function(instance){
console.log(instance);
});
答案2
得分: 1
ChartJS API实际上提供了getChart
方法来实现您想要的功能:
let chart = Chart.getChart('chart-2'); // 通过canvas ID 选择
// 或者
let canvas = document.querySelector('#chart-2');
let chart = Chart.getChart(canvas); // 使用canvas元素选择
// 您现在可以更新您的图表
chart.data.datasets[0].data = newData;
chart.data.labels = newLabels;
chart.update();
英文:
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();
答案3
得分: 0
我建议将发送到图表的所有数据存储在数组中。一旦数组更新,您可以发送以下内容给客户端,并更新图表:
> HTTP/AJAX/SOCKET.IO
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论