Can you explain to me getImageData(x, y, wx, wh).data? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can you explain to me getImageData(x, y, wx, wh).data?

I can't understand the pixels array, I read that for the first pixel at the top left there are four elements, one for red, one for green, one for blue and one for alpha values of RGBA, and that I can find the red element of a pixel by doing (x + y * width) * 4, however, when I tried this out I noticed that thet data property contains multiple arrays, not just one, I can't understand how it works, why does it have so many arrays? How do I find a pixel by it's x and y position?

22nd Feb 2021, 12:23 PM
Karak10
Karak10 - avatar
3 Answers
+ 2
data prpperty hold an 1D array-like: you access it by doing arr[(x+y*width)*4+comp], where 'comp' should be 0 for red, 1 green, 2 blue and 3 alpha... it's not a real js array, and implementation maybe organize data internally as nested array, but you'll get an 1D array-like of 4*width*heigth elements ^^
22nd Feb 2021, 12:38 PM
visph
visph - avatar
+ 2
not an array, an array-like... as internally data could be stored as nested arrays (for example), it could appear as so by iterating over data object property (when logged) ^^
22nd Feb 2021, 1:34 PM
visph
visph - avatar
0
visph when I tried it earlier on my laptop though the data property did not return an array of numbers like this, it returned a lot of nested arrays, like that: [ [0-99], [100-199], [200-299], etc ] and those arrays had more arrays in them
22nd Feb 2021, 1:33 PM
Karak10
Karak10 - avatar