问题描述
我正在创建一个带有图表的 html 网页,该图表显示电压水平不断变化.我想每秒刷新一次页面,以便条形图中的条形变为新值.我不确定如何像这样更新图表数据.到目前为止,我有以下内容:
I am creating an html web page with a chart on that shows voltage levels continuously changing. I want to refresh the page every second so that the bars in the bar chart go to the new values. I am not sure how to update the chart data like this. I have the following so far:
Chart.plugins.unregister(ChartDataLabels);
function myFunction() {
var cells = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
var voltages = [];
for (i = 0; i < 16; i++) {
voltages[i] = Math.floor(28 + Math.floor(Math.random() * 8)) / 10;
}
var colours = [];
for (i = 0; i < voltages.length; i++) {
colours[i] = getColour(voltages[i]);
}
var ctx = document.getElementById("voltageChart");
var voltageChart = new Chart(ctx, {
plugins: [ChartDataLabels],
type: "bar",
data: {
labels: cells,
datasets: [{
data: voltages,
backgroundColor: colours,
}]
},
});
function updateData(chart) {
chart.data.datasets[0].data = voltages;
chart.data.datasets[0].backgroundColor = colours;
chart.update();
}
function refreshData() {
for (i = 0; i < 16; i++) {
voltages[i] = Math.floor(28 + Math.floor(Math.random() * 8)) / 10;
}
for (i = 0; i < voltages.length; i++) {
colours[i] = getColour(voltages[i]);
}
updateData(voltageChart);
}
setInterval(refreshData, 1500);
}
推荐答案
我们可以使用 chart.data.datasets.pop()
推送新数据 chart.data.datasets.push()
然后调用 chart.js 函数 chart.update
重新渲染图形.这是示例:https://codepen.io/bhupendra1011/pen/MWwWogO?editors=1111.
We can use chart.data.datasets.pop()
and push new data chart.data.datasets.push()
and then invoke chart.js function chart.update
to re-render the graph . here is the example : https://codepen.io/bhupendra1011/pen/MWwWogO?editors=1111.
更多关于添加/删除数据这里
More on adding/removing data here
这篇关于每秒刷新一次图表数据javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!