要将单个图像传递给工作线程,我会执行以下操作
var image = ctx.getImageData(0, 0, data.width, data.height));
var tData = new Uint8ClampedArray(data.width*data.height*4);
tData.set(image.data);
let message = {function: "my function", buffer: tData.buffer}
worker.postMessage(message, [tData.buffer]);
这适用于单个图像,但现在我想使用循环发送可变数量的图像。规范中允许发送多个数组(例如 worker.postMessage(message, [array1, array2]);),但是您不能动态更改图像的数量。
let imageDataArray=[];
for(let i=0;i<images.length;i++){
var tData = new Uint8ClampedArray(data.width*data.height*4);
tData.set(images[i].data);
imageDataArray.push(tData.buffer);
}
let message = {function: "my function", buffer: imageDataArray}
worker.postMessage(message, [imageDataArray]);
但它只是无法正常工作,因为数据类型不可转移。有没有合适的方法来做到这一点?
Uncaught TypeError: Failed to execute 'postMessage' on 'Worker': Value at index 0 does not have a transferable type.