I want to merge n number of canvases horizontally and vertically. Since it's computational heavy, I want to use web worker to do this task so that it doesn't block the UI. I know that the canvases cannot be sent to web worker as they are part of the DOM. How do I achieve this, or how do I send canvases to web worker and get a newly combined canvas.
I am using the following code to stack canvases horizontally:
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
};
}