在javascript中计算出网格的坐标?

时间:2013-06-30 17:50:57

标签: javascript

如果我有一个3 x 3的50像素正方形网格,水平编号为1-9,如下所示;

| 1 | 2 | 3 |

| 4 | 5 | 6 |

| 7 | 8 | 9 |

如果我知道方形的数字比如说方形9,并且这个例子中的正方形宽度为50像素,我怎么能以编程方式根据坐标系统计算出方形的坐标? 0,从左上角开始。

在这种情况下,方形9将是x = 100y = 100

到目前为止我已经尝试了这个但是失败了,

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

2 个答案:

答案 0 :(得分:1)

通用公式为:

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

在你的情况下,因为它是一个3 x 3网格,它将是:

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

在Javascript中,不使用整数除法,您必须使用以下y

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

答案 1 :(得分:1)

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);
相关问题