user2251919
user2251919

Reputation: 675

Working out co-ordinates of a grid in javascript?

If I have a grid of 3 x 3 of 50 pixel squares which are numbered 1-9 horizontally, like below;

| 1 | 2 | 3 |

| 4 | 5 | 6 |

| 7 | 8 | 9 |

If I know the number of the square say for instance square 9, and the width of the squares in this instance 50 pixels, how can I programmatically work out the co-ordinate of the square based on a co-ordinate system of 0, 0 starting from the top left.

Square 9 in this case would be x = 100 and y = 100,

I have tried this so far but it fails,

x = (squareNumber * squareWidth)
y = (squareNumber * squareHeight)

Upvotes: 0

Views: 59

Answers (2)

sferret
sferret

Reputation: 461

var width=50,height=50;
 function gridPos(n){
      var pos={};
      pos.x=(n -1)%3*width;
      pos.y=Math.floor((n-1)/3)*height;
      return pos;
 }
pos=gridPos(8);
console.log("pos is " + pos.x + " " + pos.y);

Upvotes: 1

Artyom
Artyom

Reputation: 1599

The general formula is:

x = (squareNumber - 1) % numberOfSquaresPerRow * squareWidth
y = (squareNumber - 1) / numberOfSquaresPerCol * squareHeight

In your case, since it's a 3 x 3 grid, it would be:

x = (squareNumber - 1) % 3 * squareWidth
y = (squareNumber - 1) / 3 * squareHeight

In Javascript, which does not use integer division, you have to use the following for y:

y = Math.floor((squareNumber - 1) / 3) * squareHeight

Upvotes: 1

Related Questions