I am changing from Dygraph to Chartjs because of rendering webworkers and wish to fully multithread the graph to keep main thread empty as much as possible. I am trying to use Workers for handling data and rendering as mentioned on the Chart.js page:
https://www.chartjs.org/docs/master/general/performance/. I have problems at reusing the canvas and implementing the parallel rendering.
I am able to use Webworkers for the data but unable to get it to draw due to
Error: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID 'myChart' can be reused.
<template>
<canvas id="myCanvas"></canvas>
</template>
<script>
testGraph() {
let data = [];
const worker = new Worker(new URL('./worker.js', import.meta.url));
worker.onmessage = function(e) {
data = e.data;
// Add new data to the existing dataset
console.log(data);
myChart.update(); // Update the chart with new data
};
// Set up the chart
const ctx = document.getElementById('myChart');
const myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'TestLabel',
data: data,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}]
},
options: {
animation: false,
scales: {
x: {
type: 'linear',
position: 'bottom'
},
y: {
beginAtZero: true
}
}
}
});
setInterval(() => {
worker.postMessage('start');
}, 5000);
},
</script>
Worker.js code bellow
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
self.onmessage = function() {
var data = [];
for (let j=0;j < 10; j++) {
data.push({ x: j, y: getRandomInt(1000) });
}
postMessage(data);
};