score:3

Accepted answer

you need to import the library inside your worker's script.

for this you can use the importscripts() method.

also be sure to use the v.3 of the library as v2.x was expecting a dom htmlelement, and finally, it seems you need to set a global window variable (set it to self) in your worker:

const worker_script = `
  const window = self;
  importscripts("https://cdnjs.cloudflare.com/ajax/libs/chart.js/3.0.0-beta/chart.min.js");

  onmessage = function(event) {
    const {canvas, config} = event.data;
    const chart = new chart(canvas, config); // error for chart 

    canvas.width = 500;
    canvas.height = 500;
    chart.resize();
  };
`;
const worker_url = url.createobjecturl(new blob([worker_script], { type: "text/javascript" }));

const worker = new worker(worker_url);
const canvas = document.getelementbyid("canvas").transfercontroltooffscreen();
const config = { type:"line",data:{labels:["january","february","march","april","may","june","july"],datasets:[{label:"my first dataset",data:[65,59,80,81,56,55,40],fill:false,bordercolor:"rgb(75, 192, 192)",linetension:0.1}]} };

worker.postmessage({ canvas, config }, [canvas]);
<canvas id="canvas"></canvas>


Related Query

More Query from same tag