Find the (x,y) coordinates of an index value in an array

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:

var blockSize = 2;
var totalBlocks = (canvas.width / blockSize) * (canvas.height / blockSize);
var cursor = index % totalBlocks;
var columns = canvas.width / blockSize;
var x = (cursor % columns) * blockSize;
var y = (cursor / columns) * blockSize;

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 becomes even simpler:

var x = index % columns;
var y = index / columns;

That’s it~

Leave a Reply

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