Question

So I have my canvas and I take some image data from it like so:

// assume canvas already has an image on it
var data = ctx.getImageData(0, 0, 20, 20);

now in the data I have a lot of nonsense of which I have no idea what any of it really is because I have an array of 1600 items? Not sure what that's all about..

I want to get the average RGB value for the entire 20x20 block. How would I even go about getting that from the image data?

Was it helpful?

Solution

getImageData returns an object, which has a data property. That property is an array of values, which is what you are seeing.

Basically, it's built like this:

[
    pixel (0,0) red, pixel (0,0) green, pixel (0,0) blue, pixel (0,0) alpha,
    pixel (1,0) red, pixel (1,0) green, pixel (1,0) blue, pixel (1,0) alpha
    ......
]

And so on.

So to get the colour of pixel (X,Y), you need to get the values (Y*W+X)*4 for the red, (Y*W+X)*4+1 for the green, (Y*W+X)*4+2 for the blue, and (Y*W+X)*4+3 for the alpha, where W is the width of the image data (in your case, 20)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top