JAVASCRIPT:在Web Worker中水平和垂直合并n个HTML画布

时间:2019-02-20 12:20:03

标签: javascript canvas html5-canvas web-worker

我想水平和垂直合并n个画布。由于计算量大,因此我想使用Web Worker来执行此任务,以免阻塞UI。我知道画布无法发送给Web Worker,因为它们是DOM的一部分。如何实现这一目标,或者如何将画布发送给Web Worker并获得新合并的画布。

我正在使用以下代码将画布水平堆叠:

public getCombinedHorizontalCanvas(canvasArr: HTMLCanvasElement[]) {
    const newCanvas = document.createElement('canvas');
    const ctx = newCanvas.getContext('2d');
    const dimen = this.getDimensionsOfCanvas(canvasArr);
    newCanvas.width = dimen.combinedWidth;
    newCanvas.height = dimen.maxHeight;

    let x = 0;
    for (let id = 0; id < canvasArr.length; ++id) {
        ctx.beginPath();
        ctx.drawImage(canvasArr[id], x, 0, canvasArr[id].width, newCanvas.height);
        x += canvasArr[id].width;
    }

    return ;
}

// to get the dimensions for the canvas
private getDimensionsOfCanvas(canvas: HTMLCanvasElement[]) {
    let maxWidth = Number.NEGATIVE_INFINITY;
    let maxHeight = Number.NEGATIVE_INFINITY;
    let combinedWidth = 0;
    let combinedHeight = 0;
    for (let id = 0; id < canvas.length; ++id) {
      maxWidth = Math.max(maxWidth, canvas[id].width);
      maxHeight = Math.max(maxHeight, canvas[id].height);
      combinedHeight += canvas[id].height;
      combinedWidth += canvas[id].width;
    }

    return {
      maxHeight: maxHeight,
      maxWidth: maxWidth,
      combinedHeight: combinedHeight,
      combinedWidth: combinedWidth
    };
}

0 个答案:

没有答案