Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 942
Teiem Avatar asked Dec 29 '25 08:12

Teiem


1 Answers

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...).

like image 150
Kaiido Avatar answered Jan 01 '26 00:01

Kaiido



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!