问题描述
我不是那么熟悉的三角函数,但我只有两点在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()
或<$ c $将它们转换为整数c> 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.
这篇关于如何在Javascript中计算2D中的旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!