It is impossible to use plain RGB, but the loop in this code could be optimized by removing repetitive calculations, deviations from arrays, etc.
In general, you should not use ctx.getImageData to get the target buffer โ you generally donโt care what values โโalready exist, and ctx.createImageData should be used ctx.createImageData . If at all possible, reuse the same raw buffer for each frame.
However, since you want to pre-set the alpha values โโto 0xff (by default they are 0x00 ), and you only need to do this once, it seems that it is much more efficient to just fill the canvas and then extract the raw values โโwith getImageData .
ctx.fillStyle = '#ffffff'; // implicit alpha of 1 ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); dest = ctx.getImageData(0, 0).data
and then for each frame, you can just leave the alpha bytes intact:
var n = 4 * w * h; var s = 0, d = 0; while (d < n) { dest[d++] = src[s++]; dest[d++] = src[s++]; dest[d++] = src[s++]; d++;
You can also experiment with "looping around" (that is, repeating four string blocks several times in a while ), although the results will be different in different browsers.
Since it is very likely that your total number of pixels will be a multiple of four, just repeat the block three more times, and then while will only be evaluated for every four pixel copies.
Alnitak
source share