如果我有一个 3 x 3 的 50 像素正方形网格,水平编号为 1-9,如下所示;
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
如果我知道正方形的编号,例如正方形 9,并且本例中正方形的宽度为 50 像素,那么我如何以编程方式根据以下坐标系计算出正方形的坐标: 0, 0 从左上角开始。
本例中的方格 9 为 x = 100
和 y = 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
关于javascript - 在javascript中计算出网格的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17393172/