Web graphics often require us to work with images (bitmaps) in the form of a giant array of rgb values. However translating between the index of the array and the x,y coordinates of the bitmap can be confusing. I’ve written a couple formulas below to help you translate from index to x,y and vice versa.
Let’s say you have an array of blocks that you want to draw to a canvas. Let’s also say you want to compute the (x,y) coordinates of a specific item in the array. There’s a formula for that:
[pastacode lang=”javascript” manual=”var%20blockSize%20%3D%202%3B%0Avar%20totalBlocks%20%3D%20(canvas.width%20%2F%20blockSize)%20*%20(canvas.height%20%2F%20blockSize)%3B%0Avar%20cursor%20%3D%20index%20%25%20totalBlocks%3B%0Avar%20columns%20%3D%20canvas.width%20%2F%20blockSize%3B%0Avar%20x%20%3D%20(cursor%20%25%20columns)%20*%20blockSize%3B%0Avar%20y%20%3D%20(cursor%20%2F%20columns)%20*%20blockSize%3B” message=”” highlight=”” provider=”manual”/]
All this does is count up to the index taking into account the fact you need to wrap blocks of a certain size.
If you don’t need a specific block size and are just using single pixels as a block size, then the formula is simple:
[pastacode lang=”javascript” manual=”var%20x%20%3D%20index%20%25%20columns%3B%0Avar%20y%20%3D%20index%20%2F%20columns%3B” message=”” highlight=”” provider=”manual”/]
That’s it~
Where did `index` came from?