我有一个从API获取数据的圆环图。图表显示正常,但我不能让图表数据更新,每2秒更新一次。我尝试并搜索了许多主题,但大多数都是过时的chart.js版本,我的javascript技能很差。
Chart.js v3.9.1
const totalRunTime = current_array.MTConnectStreams.Streams.DeviceStream.ComponentStream[12].Samples.DynamicBasicData[1];
const totalTimeRemaining = current_array.MTConnectStreams.Streams.DeviceStream.ComponentStream[12].Samples.DynamicBasicData[13];
const timeRemaining = ((totalTimeRemaining / totalRunTime) * 100)
// Setup
const datapoints = [(100 - timeRemaining), timeRemaining];
const data = {
datasets: [{
data: datapoints,
backgroundColor: ['rgba(20, 121, 255, 0.7)', 'rgba(208, 208, 208, 0.5)'],
borderWidth: 1,
cutout: '70%'
}]
};
// Counter
const counter = {
id: 'counter',
beforeDraw( chart, args, options ) {
const { ctx, chartArea: { top, right, bottom, left, width, height } } = chart;
ctx.save();
ctx.font = options.fontSize + 'px ' + options.fontFamily;
ctx.textAlign = 'center';
ctx.fillStyle = options.fontColor;
ctx.fillText(datapoints[0].toFixed(3) + '%', width / 2, (height / 2) + (options.fontSize * 0.34));
}
};
// Config
const config = {
type: 'doughnut',
data,
options: {
plugins: {
legend: {
display: false
},
tooltip: {
enabled: false
},
counter: {
fontColor: '#193b68',
fontSize: '16',
fontFamily: 'Sofia Pro Medium'
}
}
},
plugins: [counter]
};
// Render init
const doughnutChart = new Chart(
document.getElementById('doughnutChart'),
config
);
setInterval(function addData(chart, data) {
chart.data.datasets.forEach((dataset) => {
dataset.data = data;
});
chart.update('none');
}, 2000
);
HTML格式
<canvas id="doughnutChart"></canvas>
1条答案
按热度按时间0kjbasz61#
它看起来好像没有更新,因为您调用了数据,并将其存储在一个变量中,从应用程序的范围来看,该变量尚未更改。
如果您将数据请求移动到一个函数,然后从
setInterval
内的初始化代码 * 和 * 中调用该函数,您应该会看到每次调用函数getData
时,数据都会更新。下面是一个符合我意思的代码版本,其中使用了
getData()
而不是datapoints
:这是一个codepen of an updating version,但使用了随机值而不是数据请求。
这可能就是问题所在,我希望这对你有帮助。
一个技巧是使用console.log来查看调用了什么,将代码放在函数中也可以通过使用
console.log
或debugger
查看调用代码的位置和时间,从而使调试变得更容易。