Finding A Pixel in Canvas Image Data

I never have time, so this will be quick.

Let’s say we want to find a pixel index amoung all that image data canvas returns with:

var imgData = ctx.getImageData(x,y,w,h);

The formula is simple:

var y = [ROW];
var x = [COLUMN];
var w = imgData.width;
var pixIdx = (y * w + x) * 4;
var pixel = imgData[pixIdx];

Basically, you need to draw this one out. Let’s say we have a 3×3 image. Each pixel would have it’s own zero based index. The width would be three. Each row would stretch from 0 – 2 and each column would stretch from 0 – 2.

pixels

 

Now let’s say we want to select the 7th pixel. We know the formula is:

index => (y * w + x)

So we can calculate the index by selecting Row 2 and Column 1. Just like battleship.

pix-index

 

The only confusing part is why we should multiply by 4 at the end! It’s simple really, there are 4 values for every pixel (r,g,b,a).

To loop through and get the index for every pixel, might look something like:

for(var x = 0, w = imgData.width; x < w; ++x) {
	for(var y = 0, h = imgData.height; y < h; ++y) {
		var pixIndex = (y * w + x) * 4;
		var r = imgData[pixIndex];
		var g = imgData[pixIndex + 1];
		var b = imgData[pixIndex + 2];
		var a = imgData[pixIndex + 3];
	}
}

That’s it.

Leave a Reply

Your email address will not be published. Required fields are marked *