简体   繁体   中英

Chart.js redraw chart for which rendering is in progress

I am using a chart.js 3.x JavaScript library for displaying charts.
I need to update the chart for which rendering is in progress .
I am using JavaScript Worker for updating the chart data.

for (var index=0;index < myjson.length;index++) {           
    chart.data.datasets[index].data.push(myjson[index]);
}
chart.update();

I am doing something like below to clean the chart dataset.

// Set the empty data and render the chart to clear the data 
for (var index=0;index < chart.data.datasets.length;index++) {           
    chart.data.datasets[index].data = [];
}
chart.update();

But I see a few of the lines are still on the chart and not cleared properly.
May be continuous drawing is causing this issue.
I have also tried to clear() and reset() the chart but no effect.
So how to clear the chart data properly and redraw new dataset.

use stop() to end the current animation loop,
then clear the data, and update the chart without animation.

see following working snippet,
once the animation progress reaches 50%,
the animation is stopped, the data is cleared, and the chart is updated without animation...

 $(document).ready(function() { var offset = [100, 100, 100, 100]; var data = [7900, 5400, 4300, 4300]; var ctx = document.getElementById('bar-chart'); var data = { labels: ['June 9', 'June 11', 'June 13', 'June 15'], datasets: [{ data: offset, backgroundColor: 'transparent' }, { data: data.map(function (value, index) { return value - offset[index]; }), backgroundColor: 'orange' }] } var chart = new Chart(ctx, { type: 'bar', data: data, options: { animation: { onProgress: function(animation) { var progress = animation.currentStep / animation.numSteps; // determine if progress is above 50% if (progress >= 0.5) { // stop current animation loop animation.chart.stop(); // remove labels and data for (var i = chart.data.labels.length - 1; i >= 0; i--) { animation.chart.data.labels.pop(); } for (var i = chart.data.datasets.length - 1; i >= 0; i--) { animation.chart.data.datasets.pop(); } // update without animation animation.chart.update(0); } } }, legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ stacked: true }] } } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta/chart.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <canvas id="bar-chart"></canvas>

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