Course contentsShow
← Web Development
Lesson 2625 of 2,98247. Data VisualizationFree lesson

Pixel Manipulation

Accessing and modifying pixel data directly with getImageData, putImageData, and ImageData objects.

Pixel Manipulation

You'll learn how to directly access and modify individual pixel color data on a Canvas element.

What Is Pixel Manipulation?

While most Canvas drawing methods work at a shape level (rectangles, paths, images), pixel manipulation lets you zoom down to the lowest level: individual pixels. You can read every pixel's red, green, blue, and alpha (transparency) values, change them, and write them back to the canvas. Think of it like editing a photo at the pixel level in Photoshop, but with code.

The Three Core Methods

getImageData(x, y, width, height) extracts a rectangular region of pixels from your canvas, returning an ImageData object. This object contains a data property—a flat array where every four consecutive values represent one pixel's RGBA channels (0-255 for each).

const ctx = canvas.getContext('2d');
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

ImageData object holds the pixel data. Its data property is a Uint8ClampedArray where pixels are stored sequentially: [R, G, B, A, R, G, B, A, ...].

// Access first pixel
const red = imageData.data[0];
const green = imageData.data[1];
const blue = imageData.data[2];
const alpha = imageData.data[3];

putImageData(imageData, x, y) writes modified pixel data back to the canvas.

// Invert all colors
for (let i = 0; i < imageData.data.length; i += 4) {
  imageData.data[i] = 255 - imageData.data[i];     // R
  imageData.data[i+1] = 255 - imageData.data[i+1]; // G
  imageData.data[i+2] = 255 - imageData.data[i+2]; // B
}
ctx.putImageData(imageData, 0, 0);

Common Use Cases

Create custom filters (grayscale, brightness), analyze image content, implement effects impossible with standard drawing methods, or build pixel-perfect collision detection.

Key Takeaway: Pixel manipulation gives you raw access to canvas image data through getImageData, the ImageData object's flat RGBA array, and putImageData to render your modifications.