JavaScript: RGBA pixel arrays and Uint8ClampedArray

In the browser, canvas ImageData stores an image as one flat Uint8ClampedArray with four bytes per pixel in the order red, green, blue, alpha. Pixel number p starts at index 4·p. Image-processing code walks this array in steps of four.

JavaScript
const pixels = new Uint8ClampedArray([
  255, 0, 0, 255,
  0, 255, 0, 255,
  0, 0, 255, 255,
  255, 255, 255, 255,
]);

for (let i = 0; i < pixels.length; i += 4) {
  const gray = Math.round(0.299 * pixels[i] + 0.587 * pixels[i + 1] + 0.114 * pixels[i + 2]);
  pixels[i] = gray;
  pixels[i + 1] = gray;
  pixels[i + 2] = gray;
}
console.log(pixels.join(","));

const clamped = new Uint8ClampedArray([300, -20, 127.6]);
console.log(clamped.join(","));
Read the full lesson