1

我正在尝试从 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 中取出并放到画布上?

4

1 回答 1

2

如果您拥有的是原始 RGBA 像素数据,那么您只需要从 Uint16Array创建一个 ImageData并将其放在您的 canvas 上

const img_width = 50;
const img_height = 50;
const data = new Uint16Array((img_width * img_height) * 2 );
// make some noise
crypto.getRandomValues(data);

const canvas = document.getElementById('canvas');
canvas.width = img_width;
canvas.height = img_height;
const ctx = canvas.getContext('2d');
const img = new ImageData(
  new Uint8ClampedArray(data.buffer),
  img_width,
  img_height
);
ctx.putImageData( img, 0, 0 );
<canvas id="canvas"></canvas>

您的代码没有产生任何错误,因为您没有在听它。如果你error为你的事件添加一个监听器imageObject,你会看到它无法加载你提供给它的东西,因为图像不仅仅是原始像素数据,它还有标题,至少可以告诉图像的大小。

于 2020-03-29T08:06:24.753 回答