JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<div style="width:500px;height:500px">
<canvas id="canvasLine"></canvas>
</div>
JavaScript
// y 軸的顯示
var yAxis= [];
// 資料集合,之後只要更新這個就好了。
// 因為兩組資料,所以規劃成datas1 ,datas2
var datas1=[];
var datas2=[];
var ctx = document.getElementById('canvasLine').getContext('2d');
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels:yAxis,
datasets:
[
{
label: '測試資料',
data: datas1,
fill:false,
borderColor:"#FFFF00",
backgroundColor: "#FFFF00"
},
{
label: '測試資料2',
data: datas2,
fill:false,
borderColor:"#00FF00",
backgroundColor: "#00FF00"
},
]
}
});
//時間格式
var timeFormat = 'HH:mm:ss';
function appendData()
{
//超過10 個,就把最早進來的刪掉
if(yAxis.length>10){
yAxis.shift();
datas2.shift();
datas1.shift();
}
//推入y 軸新的資料
yAxis.push(new moment().format(timeFormat));
//推入一筆亂數進資料 1~1000
datas1.push(Math.floor(Math.random() *1000) + 1);
datas2.push(Math.floor(Math.random() *1000) + 1);
//更新線圖
lineChart.update();
}
//每秒做一次
setInterval(appendData,300);