問題描述
我對三角學不是很熟悉,但我只有兩個點可以在 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.
這篇關于如何在Javascript中計算二維旋轉的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!