我正在构建一个实时Chart JS图表,该图表用于显示数据并每隔几秒钟更新一次,我在下面附加了我的Chart JS代码,该代码可以在页面加载时随机化数据,我有一个label数组,需要将其更改为不管当前的日期/时间是什么,并且每隔X个项目就删除前一个,以便该图实质上是一个显示实时统计信息的时间轴,我首先试图弄清楚如何使我的图表每隔几更新一次数据秒,不确定如何执行此操作:
$(document).ready(function(){
// Random data on page load
var datasetValue = [];
var count = 70;
for (var j = 0; j < count; j++) {
datasetValue[j] = {
data: [
Math.round(Math.random() * 100),
Math.round(Math.random() * 100)-10,
Math.round(Math.random() * 100),
Math.round(Math.random() * 100)-10,
Math.round(Math.random() * 100),
Math.round(Math.random() * 100)-10,
Math.round(Math.random() * 100)
]
}
}
var mydata = {
datasets: datasetValue
}
// Our chart
var ctx = document.getElementById('status-chart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "Max",
fill: false,
borderColor: '#f44336',
data: mydata.datasets[1].data,
}, {
label: "Free",
fill: false,
borderColor: '#4CAF50',
data: mydata.datasets[3].data,
}, {
label: "Total",
fill: false,
borderColor: '#607D8B',
data: mydata.datasets[2].data,
}, {
label: "Used",
fill: false,
borderColor: '#2196F3',
data: mydata.datasets[4].data,
}]
},
options: {
legend: {
display: true,
labels: {
fontColor: '#000'
}
}
}
});
});
答案 0 :(得分:0)
您可以使用chart.update()方法分配新的数据集
<canvas id="myChart" width="400" height="250"></canvas>
<input type="button" value="New Data" onclick="RandomData()">
var canvas = document.getElementById('myChart');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My dataset",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 5,
pointHitRadius: 10,
data: [65, 59, 80, 0, 56, 55, 40],
}
]
};
function RandomData(){
var newData=[];
for(var i=0;i<7;i++){
newData.push(Math.round(Math.random() * 100))
}
myLineChart.data.datasets[0].data =newData;
myLineChart.update();
}
var option = {
showLines: true
};
var myLineChart = Chart.Line(canvas,{
data:data,
options:option
});
请观看演示here