我正在尝试从 JavaScript 中的 Uint16Array 渲染图像。我没有收到任何捕获的错误,但没有渲染到画布上。
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const bufferMemoryAllocation = cellCount*2; //double the size 2bytes--16bits--per memory slot
const bitArray = new SharedArrayBuffer(bufferMemoryAllocation); // double the number of cells
const pixelData = new SharedArrayBuffer(bufferMemoryAllocation);
const pixelDataCanvas = new Uint16Array(pixelData);
const videoResolutions = [{name: "test", height: 1000, width:1000},{name:"1080", height: 1080, width:1920},{name:"4k", height: 2160, width:3840}];
canvas.height = videoResolutions[2].height;
canvas.width = videoResolutions[2].width;
const cellScale = 2;
const drawHeight = Math.floor(canvas.height/cellScale);
const drawWidth = Math.floor(canvas.width/cellScale);
const cellCount=drawHeight*drawWidth;
function renderToCanvas()
{
ctx.drawImage(renderToImage(pixelDataCanvas),0,0,drawWidth,drawHeight);
}
function renderToImage(pixelDataReffernce)
{let imageObject = new Image(canvas.height,canvas.width);
let imageString = 'data:image/bmp;base64,'+btoa(pixelDataReffernce);
imageObject.src = imageString;
// console.log(imageObject);
return imageObject;
}
pixelDataReference 控制台输出到::
Uint16Array(2073600) [0, 0, 0, 0, 0, 0, 0, 0, 1024, 1024, 1024, 0, 0, 0, 0, 1024, 0, 0, 0, 1024, 1024, 1024, 0, 0, 0, 0, 0, 1024, 0, 0, 0, 0, 1024, 0, 1024, 1024, 1024, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1024, 0, 0, 0...
编辑_
那是我没有使用 4 通道颜色阵列,而是使用颜色的二进制通道。解决方案是将记录颜色的大小增加到 4 个字节长,并在主线程上查看为 1 个字节长。但是:如果我尝试使用
new Uint8ClampedArray(data.buffer) 访问 SharedMemory,我会收到以下控制台警告。
Uncaught TypeError: Failed to construct 'ImageData': The provided ArrayBufferView value must not be shared.
所以下一步是在主线程上创建临时数组;
const pixelTransViewer = new Uint8Array(pixelData);
const tA = new Uint8ClampedArray(data.buffer);
for(let i=0;i<tA.length;i++)
{
for(let j=0;j < 8;j++)
{
tA[i]=setBitState(tA[i],j,checkBit(pixelTransViewer[i],j));
}
}
const img = new ImageData(tA, span);
但这实际上只是将信息从 sharedMememory 重新压缩到每次渲染的新内存插槽......有效地将相同的信息绘制到数组中两次。有没有更快的方法让我将 pixelData 从 sharedMemory 中取出并放到画布上?