如何在使用打字稿的React中使用WebWorkers

问题描述 投票:0回答:1

我有一些繁重的画布代码,我想将它们卸载到WebWorker中。当我按照this page中的示例进行操作时,我将工作者打字稿文件的路径传递给了构造函数New Worker("./PaintCanvas.ts")该代码已成功编译,但是当它运行时,工作进程似乎未正确找到该代码,因为它抛出一个错误,说Uncaught SyntaxError: Unexpected token '<',并且它似乎正在尝试执行的文件实际上是我的index.html文件。这是我要从中运行工作程序的组件:

import React, { RefObject } from 'react';
//eslint-disable-next-line import/no-webpack-loader-syntax
import * as workerPath from "file-loader?name=[name].js!./PaintCanvas";
import './Canvas.css';

interface IProps {

}

interface IState {

}

class Canvas extends React.Component<IProps, IState> {
    private canvasRef: RefObject<HTMLCanvasElement>;
    private offscreen?: OffscreenCanvas;
    private worker?: Worker;

    constructor(props: IProps) {
        super(props);
        this.canvasRef = React.createRef();

        this.resizeListener = this.resizeListener.bind(this);

        window.addEventListener('resize', this.resizeListener);
    }

    componentDidMount() {
        let canvas = this.canvasRef.current;
        if (canvas) {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
            this.offscreen = canvas.transferControlToOffscreen();
            this.worker = new Worker("./PaintCanvas.ts");
            this.worker.postMessage(this.offscreen, [this.offscreen]);
        }

    }

    resizeListener() {
        let canvas = this.canvasRef.current;
        if (canvas) {
            canvas.width = window.innerWidth > canvas.width ? window.innerWidth : canvas.width;
            canvas.height = window.innerHeight > canvas.height ? window.innerHeight : canvas.height;
            this.offscreen = canvas.transferControlToOffscreen();
            this.worker = new Worker("./PaintCanvas.ts");
            this.worker.postMessage(this.offscreen, [this.offscreen]);
        }
    }

    render() {
        return (
            <>
                <canvas className="noiseCanvas" ref={this.canvasRef}/>
                <div className="overlay">
                </div>
            </>
        );
    }
}

export default Canvas;

这是我要加载的工作程序:

export default class PaintCanvas extends Worker {
    private canvas?: OffscreenCanvas;
    private intervalId?: number;
    private frame: number;
    private frameSet: number;
    private noiseData: ImageData[][];
    private noiseNum: number[];
    private overlayFrame: number[];
    private overlayData: Uint8ClampedArray[][];
    private overlayNum: number[];
    private workers: (Worker|undefined)[];

    constructor(stringUrl: string | URL) {
        super(stringUrl);
        this.frame = 0;
        this.frameSet = 0;
        this.noiseData = [[], [], []];
        this.noiseNum = [0, 0, 0];
        this.overlayFrame = [0, 0, 0];
        this.overlayData = [[], [], []];
        this.overlayNum = [0, 0, 0];

        this.workers = [undefined, undefined, undefined];
    }

    onmessage = (event: MessageEvent) => {
        this.canvas = event.data;
        this.frame = 0;
        this.frameSet = 0;
        this.noiseData = [[], [], []];
        this.noiseNum = [0, 0, 0];
        this.overlayFrame = [0, 0, 0];
        this.overlayData = [[], [], []];
        this.overlayNum = [0, 0, 0];
        if (this.workers[0]) {
            this.workers[0].terminate();
        }
        if (this.workers[1]) {
            this.workers[1].terminate();
        }
        if (this.workers[2]) {
            this.workers[2].terminate();
        }
        this.makeNoise(0);
        this.makeNoise(1);
        this.makeNoise(2);
        if (this.intervalId) {
            window.clearInterval(this.intervalId);
        }
        this.intervalId = window.setInterval(this.paintNoise, 100);
    }

    makeNoise(index: number) {
        if (this.canvas) {
            const width = this.canvas.width;
            const height = this.canvas.height;
            this.workers[index] = new Worker("./FillCanvas.ts");
            if (this.workers[index]) {
                this.workers[index]!.onmessage = (event) => {
                    if (this.overlayNum[index] < 4 || !event.data[0]) {
                        this.overlayData[index].push(event.data);
                        this.overlayNum[index]++;
                        if (this.overlayNum[index] < 4) {
                            this.workers[index]!.postMessage([width, height]);
                        } else {
                            this.workers[index]!.postMessage([width, height, new Uint8ClampedArray(width * height * 4), this.overlayData[index][0]]);
                            this.overlayFrame[index]++;
                        }
                    } else {
                        if (event.data[0]) {
                            this.noiseData[index].push(new ImageData(event.data[0], width, height));
                            this.noiseNum[index]++;
                            if (this.noiseNum[index] < 30) {
                                this.workers[index]!.postMessage([width, height, event.data[1], this.overlayData[index][Math.ceil(this.overlayFrame[index] / 4) % 4]]);
                                this.overlayFrame[index]++;
                            } else {
                                this.workers[index] = undefined;
                            }
                        }
                    }
                }
                this.workers[index]!.postMessage([width, height]);
            }
        }
    }

    paintNoise() {
        if (this.noiseNum[0] > 10) {
            this.frame++;
            if (this.frame % this.noiseNum[this.frameSet % 3] === 0) {
                this.frameSet++;
            }
            if (this.canvas) {
                let ctx = this.canvas.getContext("2d");
                if (ctx) {
                    ctx.putImageData(this.noiseData[this.frameSet % 2][this.frame % this.noiseNum[this.frameSet % 2]], 0, 0);
                }
            }
        }
    }
}

您可以看到,只要工作正常,我的工人也将创建自己的工人。您还应该注意到在顶部的workerPath导入。几年前,我尝试实现this similar stackoverflow question的最佳答案,这的确使代码本身可见,但是只要代码仍然是打字稿模块,它就不会起作用。相反,我尝试仅使用类的构造函数实例化worker,例如new PaintCanvas(),但这仍然需要一个url,并且它仍然只能找到index.html文件。我还尝试将工作文件放在react公共文件夹中,并使用公共URL对其进行引用。 tsconfig文件自动注意到了这一点,并将文件添加到“ include”部分,我认为这看起来很有希望,但它仍然只是尝试执行index.html。所以我的问题是,是否有一种惯用的非hacky方式来以响应方式在打字稿中实施Web Worker,还是我应该使用在其他地方看到的一种hacky方法?我知道Web Worker API刚刚成熟,因此希望不再需要我在网上找到很多答案的解决方法。

reactjs typescript webpack web-worker
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.