Introduction to context.getImageData

suggest change

The canvas gives you the ability to fetch and change the color of any pixel on the canvas.

You can use Canvas’s pixel manipulation to:

Common issues:

Getting pixel colors

Use getImageData to fetch the pixel colors for all or part of your canvas content.

The getImageData method returns an ImageData object.

The imageData object has a .data property that contains the pixel color information.

The data property is a Uint8ClampedArray containing the Red, Green, Blue & Alpha (opacity) color data for all requested pixels.

// determine which pixels to fetch (this fetches all pixels on the canvas)
var x=0;
var y=0;
var width=canvas.width;
var height=canvas.height;

// Fetch the imageData object 
var imageData = context.getImageData(x,y,width,height);

// Pull the pixel color data array from the imageData object
var pixelDataArray = imageData.data;

You can get position of any [x,y] pixel within data array like this:

// byte index of pixel [x,y]; each pixel is 4 bytes (R, G, B, A)
var n = (y * width + x) * 4;

And then you can fetch that pixel’s red, green, blue & alpha values like this:

// the RGBA info for pixel [x,y]
var red=pixelDataArray[n];
var green=pixelDataArray[n+1];
var blue=pixelDataArray[n+2];
var alpha=pixelDataArray[n+3];

An Illustration showing how the pixel data array is structured

context.getImageData is illustrated below for a small 2x3 pixel sized canvas:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents