JSFiddle - React, Tailwind, and code Playground
by no2don
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:800px;height:600px">
<canvas id="canvasLine"></canvas>
</div>
JavaScript
// y 軸的顯示
var yAxis= [];
// 資料集合,之後只要更新這個就好了。
var datas=[];
var ctx = document.getElementById('canvasLine').getContext('2d');
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels:yAxis,
datasets: [{
label: '測試資料',
data: datas,
backgroundColor: "rgba(0,148,255,0.6)"
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: '垂直軸的資料名稱'
},
ticks: {
beginAtZero: false,
callback: function (value, index, values) {
return value.toLocaleString();
}
}
}]
},
tooltips: {
mode: 'label',
label: 'mylabel',
callbacks: {
label: function (tooltipItem, data) {
return tooltipItem.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
}
}
}
});
//時間格式
var timeFormat = 'HH:mm:ss';
function appendData()
{
//超過10 個,就把最早進來的刪掉
if(yAxis.length>10){
yAxis.shift();
datas.shift();
}
//推入y 軸新的資料
yAxis.push(new moment().format(timeFormat));
//推入一筆亂數進資料
datas.push(Math.floor(Math.random() *100000000) + 1);
//更新線圖
lineChart.update();
}
...