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:

[pastacode lang=”javascript” manual=”var%20imgData%20%3D%20ctx.getImageData(x%2Cy%2Cw%2Ch)%3B” message=”” highlight=”” provider=”manual”/]

The formula is simple:

[pastacode lang=”javascript” manual=”var%20y%20%3D%20%5BROW%5D%3B%0Avar%20x%20%3D%20%5BCOLUMN%5D%3B%0Avar%20w%20%3D%20imgData.width%3B%0Avar%20pixIdx%20%3D%20(y%20*%20w%20%2B%20x)%20*%204%3B%0Avar%20pixel%20%3D%20imgData%5BpixIdx%5D%3B” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”javascript” manual=”for(var%20x%20%3D%200%2C%20w%20%3D%20imgData.width%3B%20x%20%3C%20w%3B%20%2B%2Bx)%20%7B%0A%09for(var%20y%20%3D%200%2C%20h%20%3D%20imgData.height%3B%20y%20%3C%20h%3B%20%2B%2By)%20%7B%0A%09%09var%20pixIndex%20%3D%20(y%20*%20w%20%2B%20x)%20*%204%3B%0A%09%09var%20r%20%3D%20imgData%5BpixIndex%5D%3B%0A%09%09var%20g%20%3D%20imgData%5BpixIndex%20%2B%201%5D%3B%0A%09%09var%20b%20%3D%20imgData%5BpixIndex%20%2B%202%5D%3B%0A%09%09var%20a%20%3D%20imgData%5BpixIndex%20%2B%203%5D%3B%0A%09%7D%0A%7D” message=”” highlight=”” provider=”manual”/]

That’s it.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.