在 Web Worker 中使用 Chart.js

Using Chart.js in Web Worker

我正在尝试使用 Worker 使用 Chart.js 绘制图表,如 Chart.js 页面所述:
https://www.chartjs.org/docs/master/general/performance/
部分:使用 Web Worker 进行并行渲染(仅限 Chrome)

但是在 worker.js 文件中我得到一个错误:

Uncaught ReferenceError: Chart is not defined

我在 worker.js 中有以下代码:

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

    canvas.width = 100;
    canvas.height = 100;
    chart.resize();
};

您需要在工作人员的脚本中导入库。

为此,您可以使用 importScripts() 方法。

还请务必使用库的 v.3,因为 v2.x 需要一个 DOM HTMLElement,最后,您似乎需要设置一个全局 window 变量(将其设置为 self)在您的 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>