Thursday, 4 August 2022

Efficiently update a canvas with RGB or grayscale data (but not RGBA)

I have a <canvas> that I'm updating every 100 ms with bitmap image data coming from a HTTP request:

var ctx = canvas.getContext("2d");

setInterval(() => {
    fetch('/get_image_data').then(r => r.arrayBuffer()).then(arr => {
        var byteArray = new Uint8ClampedArray(arr);
        var imgData = new ImageData(byteArray, 500, 500);
        ctx.putImageData(imgData, 0, 0);
    });
}, 100);

This works when /get_image_data gives RGBA data. In my case, since alpha is always 100%, I don't send A channel through the network. Question:

  • how to efficiently do this when the request delivers RGB binary data?
  • and also when the request delivers grayscale binary data?

(Can we avoid a for loop which might be slow in Javascript for megabytes of data 10 times per second?)

Example in the grayscale => RGBA case: each input value ..., a, ... should be replaced by ..., a, a, a, 255, ... in the output array.



from Efficiently update a canvas with RGB or grayscale data (but not RGBA)

No comments:

Post a Comment