javascriptcanvasarraybufferimagedatasharedarraybuffer

convert SharedArrayBuffer to normal ArrayBuffer


I am trying to create a new ImageData from a Uint8ClampedArray based on a SharedArrayBuffer, since the ImageData constructor doesnt accept a Uint8ClampedArray based on a SharedArrayBuffer I have to convert it to a normal ArrayBuffer somehow.

Any Ideas how I can convert the SharedArrayBuffer to a normal ArrayBuffer or how I could create ImageData with a SharedArrayBuffer?


Solution

  • You have to copy that data in its own buffer that the context will own entirely.

    You can do so by just calling .slice() on the Uint8ClampedArray you have from the SAB:

    const sab = new SharedArrayBuffer( 50 * 50 * 4 );
    const arr = new Uint8ClampedArray( sab );
    const img = new ImageData( arr.slice(), 50, 50 );
    

    Or if you are going to draw the content of this SAB multiple times, then create once a fixed ArrayBuffer and fill it with the SAB's content:

    const sab = new SharedArrayBuffer( 50 * 50 * 4 );
    const sab_view = new Uint8ClampedArray( sab );
    
    const ab = new ArrayBuffer(sab.byteLength);
    const arr = new Uint8ClampedArray( ab );
    const img = new ImageData( arr, 50, 50 );
    // later when sab has new content being set
    arr.set(sab_view, 0);
    

    Live example (source)

    (outsourced because SharedArrayBuffer requires COOP, that StackSnippet is not gonna give us...).