can anyone help me to implement a web worker?
Main Code:
dataset = "dataset" + document.getElementById("dataset").value
const config = {
xAxis: {
type: 'category',
data: Object.keys(window[dataset])
},
yAxis: {
type: 'value'
},
series: [
{
data: Object.values(window[dataset]),
type: 'line'
}
]
};
const worker1 = new Worker('worker/echarts1.worker.js');
const canvasEl = document.getElementById("offscreenCanvas1");
console.log(canvasEl);
const offscreenCanvas = canvasEl.transferControlToOffscreen();
worker1.postMessage({ canvas: offscreenCanvas, config }, [offscreenCanvas]);
Web Worker (echarts1.worker.js)
importScripts('https://cdn.jsdelivr.net/npm/echarts@5.3.3/dist/echarts.js');
onmessage = function (event) {
console.log("Started Worker");
const { canvas, config } = event.data;
const chart = new echarts.init(canvas);
chart.setOption(config);
console.log("Finished Worker");
};
While Executing I'm facing the below error in the console.
You are transferring a (possible) HTMLCanvasElement ( <canvas>
), not an OffscreenCanvas.
To get the OffscreenCanvas out of that HTMLCanvasElement, you need to call its .transferControlToOffscreen()
method:
const canvasEl = document.getElementById("chart-container1");
const offscreenCanvas = canvasEl.transferControlToOffscreen();
const worker1 = new Worker('echarts1.worker.js');
worker1.postMessage({ canvas: offscreenCanvas, config }, [offscreenCanvas]);
(If the element with an id ""chart-container1"
isn't a <canvas>
, then you need to target one instead.)
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.