我不太熟悉三角函数,但我只有两个点可以在2D中旋转:
*nx, ny
. -
. -
. angle -
*cx,cy.................*x,y
cx,cy =旋转中心
x,y=当前x,y
nx,ny =新坐标
如何在某个角度计算新的点?
发布于 2013-07-02 02:31:02
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坐标。接下来的两个参数是我们要旋转的点的坐标。最后一个参数是角度,以度为单位。
例如,我们将取点(2,1),并将其绕点(1,1)顺时针旋转90度。
rotate(1, 1, 2, 1, 90);
// > [1, 0]
关于此函数的三点注意事项:
angle
应为正。对于逆时针旋转(就像您提供的图表中那样),它应该是负的。旋转( 0,0,5,0,90);// > 3.061616997868383e-16,-5
因此,结果数组的两个元素都应该是一个浮点数。您可以使用Math.round()
、Math.ceil()
或Math.floor()
as needed.
发布于 2013-07-02 02:15:48
首先,将旋转中心转换为origin
步骤1
你的新观点是
步骤2
步骤3
平移回原始旋转中心:
要获得更深层次的解释,请参阅this。
发布于 2018-04-03 21:40:30
上面被接受的答案对我不起作用,旋转是颠倒的,这里是工作函数
/*
CX @ Origin X
CY @ Origin Y
X @ Point X to be rotated
Y @ Point Y to be rotated
anticlock_wise @ to rotate point in clockwise direction or anticlockwise , default clockwise
return @ {x,y}
*/
function rotate(cx, cy, x, y, angle,anticlock_wise = false) {
if(angle == 0){
return {x:parseFloat(x), y:parseFloat(y)};
}if(anticlock_wise){
var radians = (Math.PI / 180) * angle;
}else{
var radians = (Math.PI / -180) * angle;
}
var cos = Math.cos(radians);
var sin = Math.sin(radians);
var nx = (cos * (x - cx)) + (sin * (y - cy)) + cx;
var ny = (cos * (y - cy)) - (sin * (x - cx)) + cy;
return {x:nx, y:ny};
}
https://stackoverflow.com/questions/17410809
复制相似问题