如何在Javascript中计算二维旋转
我对三角学不是很熟悉,但我只有两个点可以在 2D 中旋转:
I am not so familiar trigonometry, but I have only two points to rotate in 2D:
*nx, ny
. -
. -
. angle -
*cx,cy.................*x,y
cx, cy = 旋转中心
x,y = 当前 x,y
nx, ny = 新坐标
cx, cy = rotation center
x,y = current x,y
nx, ny = new coordinates
如何计算某个角度的新点?
How to calculate new points in a certain angle?
推荐答案
function rotate(cx, cy, x, y, angle) {
var radians = (Math.PI / 180) * angle,
cos = Math.cos(radians),
sin = Math.sin(radians),
nx = (cos * (x - cx)) + (sin * (y - cy)) + cx,
ny = (cos * (y - cy)) - (sin * (x - cx)) + cy;
return [nx, ny];
}
前两个参数是中心点(第二个点将围绕其旋转的原点)的 X 和 Y 坐标.接下来的两个参数是我们将要旋转的点的坐标.最后一个参数是角度,以度为单位.
The first two parameters are the X and Y coordinates of the central point (the origin around which the second point will be rotated). The next two parameters are the coordinates of the point that we'll be rotating. The last parameter is the angle, in degrees.
作为示例,我们将取点 (2, 1) 并将其围绕点 (1, 1) 顺时针旋转 90 度.
As an example, we'll take the point (2, 1) and rotate it around the point (1, 1) by 90 degrees clockwise.
rotate(1, 1, 2, 1, 90);
// > [1, 0]
关于这个函数的三个注意事项:
Three notes about this function:
对于顺时针旋转,最后一个参数
angle
应该是正数.对于逆时针旋转(如您提供的图表),它应该是负数.
For clockwise rotation, the last parameter
angle
should be positive. For counterclockwise rotation (like in the diagram you provided), it should be negative.
请注意,即使您提供的参数应该产生一个坐标是整数的点——即将点 (5, 0) 围绕原点 (0, 0) 旋转 90 度,这应该产生 (0, -5) -- JavaScript 的舍入行为意味着任何一个坐标仍然可能是一个非常接近预期整数的值,但仍然是一个浮点数.例如:
Note that even if you provide arguments that should yield a point whose coordinates are whole numbers -- i.e. rotating the point (5, 0) by 90 degrees about the origin (0, 0), which should yield (0, -5) -- JavaScript's rounding behavior means that either coordinate could still be a value that's frustratingly close to the expected whole number, but is still a float. For example:
rotate(0, 0, 5, 0, 90);
// > [3.061616997868383e-16, -5]
因此,结果数组的两个元素都应该是浮点数.您可以根据需要使用 Math.round()
、Math.ceil()
或 Math.floor()
将它们转换为整数.
For this reason, both elements of the resulting array should be expected as a float. You can convert them to integers using Math.round()
, Math.ceil()
, or Math.floor()
as needed.
最后,请注意,此函数假定 笛卡尔坐标系,这意味着值当您在坐标平面中向上"时,Y 轴上的值会变得更高.在 HTML/CSS 中,Y 轴是倒置的——当您将页面向下移动时,Y 轴上的值会变高.
Finally, note that this function assumes a Cartesian coordinate system, meaning that values on the Y axis become higher as you go "up" in the coordinate plane. In HTML / CSS, the Y axis is inverted -- values on the Y axis become higher as you move down the page.
相关文章