我正在构建一个实时的Chart JS图表,它用于显示数据并每隔几秒更新一次,我附上下面的图表JS代码,它随机化了页面加载的数据,我有一个标签数组,我需要更改为当前的日期/时间是,并且在每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'
}
}
}
});
});
您可以使用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