ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

SVG & HTML5 Canvas Tutorial• 7 min read

Canvas Pixel Manipulation: getImageData & Filters

Direct Uint8ClampedArray RGBA access, grayscale filters, and image inversion

Canvas grants direct access to its underlying raw RGBA byte buffer via ctx.getImageData(), enabling custom real-time computer vision filters and photo effects.

The ImageData Buffer Layout

ctx.getImageData(x, y, w, h) returns an ImageData object whose .data property is a one-dimensional Uint8ClampedArray.

Every pixel is represented by 4 sequential bytes: Red (data[i]), Green (data[i+1]), Blue (data[i+2]), and Alpha (data[i+3]).

Index formula for coordinate (x, y): i = (y * width + x) * 4.

Grayscale Image Filter Algorithm
function applyGrayscale(ctx, width, height) {
  const imgData = ctx.getImageData(0, 0, width, height);
  const pixels = imgData.data;

  // Step through pixels 4 bytes at a time (RGBA)
  for (let i = 0; i < pixels.length; i += 4) {
    const r = pixels[i];
    const g = pixels[i + 1];
    const b = pixels[i + 2];
    
    // Perceived luminance formula (ITU-R BT.601)
    const gray = 0.299 * r + 0.587 * g + 0.114 * b;
    
    pixels[i] = gray;     // R
    pixels[i + 1] = gray; // G
    pixels[i + 2] = gray; // B
  }

  // Write modified pixels back to the canvas
  ctx.putImageData(imgData, 0, 0);
}
Direct byte manipulation executes thousands of pixel calculations per millisecond.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

How many bytes in the `ImageData.data` array represent a single pixel on the canvas?