[Chartjs]-Using Chart.js in Web Worker

4👍

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>

Leave a comment