用javascript计算网格的坐标

Working out co-ordinates of a grid in javascript?

本文关键字:坐标 网格 计算 javascript      更新时间:2023-09-26

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

|1|2|3|

|4|5|6|

|7 | 8 | 9 |

如果我知道正方形的数量,比如正方形9,以及正方形的宽度,在这个例子中是50个像素,我如何根据从左上角开始的坐标系0,0,以编程的方式计算出正方形的坐标。

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

到目前为止,我已经尝试过了,但失败了,

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

一般公式为:

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
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);