我有一个无尽的网格,需要一个 JavaScript 函数来获取起点和终点区域内的坐标。网格看起来像这样。
_______________________
| | | |
| -1,-1 | 0,-1 | 1,-1 |
|_______|_______|_______|
| | | |
| -1,0 | 0,0 | 1,0 |
|_______|_______|_______|
| | | |
| -1,1 | 0,1 | 1,1 |
|_______|_______|_______|
假设我想要从 (-1,-1) 到 (0,0) 的所有坐标。在本例中,我将获得 4 个值 (-1,-1)、(0,-1)、(-1,0)、(0,0)。
我知道这是基础数学,但我在这里找不到聪明的解决方案。
最佳答案
你可以尝试这样的事情:
function GetCoordinatesBetween(xStart, xEnd, yStart, yEnd) {
var curX = xStart;
var curY = yStart;
var res = []; // Array for result coordinates
while (curX <= xEnd) {
while (curY <= yEnd) {
res.push({ x: curX, y: curY });
curY++;
}
curX++;
curY = yStart;
}
return res;
}
此函数按以下格式将坐标返回为数组:
[
0: { x: -1, y: -1},
1: { x: -1, y: 0},
...
]
关于javascript - 获取网格的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21459807/