简体   繁体   中英

Chart.js doesn't show anything

I'm trying to periodically update a chart. The data is making into the dataset but I can't get it to draw the chart. What am I doing wrong?

 const ctx = document.querySelector('#apichart canvas').getContext('2d'); const apichart = new Chart(ctx, { type: 'line', data: {datasets:[{ label:'Pressure', data: [1025,1000], fill:false, borderColor: 'rgb(75, 192, 192)', tension:0.1 }]}, options: { scales: { y: { beginAtZero: true } } } }); setInterval(function run(){ apichart.data.datasets[0].data.push(1025 * Math.random()); apichart.update(); }, 10000);
 #apichart{background:#777; position:absolute; top:0; right:0; bottom:0; left:0;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.min.js"></script> <div id="apichart"> <canvas></canvas> </div>

I think this problem related to labels, so I have add labels array and update them in setInterval each time and it works.

 const ctx = document.querySelector('#apichart canvas').getContext('2d'); const apichart = new Chart(ctx, { type: 'line', data: {labels: [1, 2], datasets:[{ label:'Pressure', data: [1025,1000], fill:false, borderColor: 'rgb(75, 192, 192)', tension:0.1 }]}, options: { scales: { y: { beginAtZero: true } } } }); setInterval(function run(){ apichart.data.labels.push(Math.random()); apichart.data.datasets[0].data.push(1025 * Math.random()); apichart.update(); }, 1000);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.min.js"></script> <div id="apichart"> <canvas></canvas> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM