Dig*_*kam 28 javascript trigonometry rotation
我不是那么熟悉的三角函数,但我在2D中只有两个点可以旋转:
*nx, ny
. -
. -
. angle -
*cx,cy.................*x,y
Run Code Online (Sandbox Code Playgroud)
cx,cy =旋转中心
x,y =当前x,y
nx,ny =新坐标
如何计算某个角度的新点?
the*_*ion 82
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];
}
Run Code Online (Sandbox Code Playgroud)
前两个参数是中心点的X和Y坐标(第二个点将围绕其旋转的原点).接下来的两个参数是我们将要旋转的点的坐标.最后一个参数是角度,以度为单位.
例如,我们将取点(2,1)并将其绕点(1,1)顺时针旋转90度.
rotate(1, 1, 2, 1, 90);
// > [1, 0]
Run Code Online (Sandbox Code Playgroud)
关于此功能的三个注释:
对于顺时针旋转,最后一个参数angle应为正.对于逆时针旋转(如您提供的图表中所示),它应为负数.
请注意,即使您提供的参数应该产生一个坐标为整数的点 - 即将点(5,0)绕原点(0,0)旋转90度,这应该产生(0,-5) - - JavaScript的舍入行为意味着任何一个坐标仍然可能是一个令人沮丧地接近预期整数的值,但仍然是一个浮点数.例如:
rotate(0, 0, 5, 0, 90);
// > [3.061616997868383e-16, -5]
Run Code Online (Sandbox Code Playgroud)
因此,结果数组的两个元素都应该是float.您可以使用它们转换为整数Math.round(),Math.ceil()或Math.floor()需要.
最后,请注意,此函数采用笛卡尔坐标系,这意味着当您在坐标平面中"向上"时,Y轴上的值会变得更高.在HTML/CSS中,Y轴反转 - 当您向下移动页面时,Y轴上的值会变得更高.
步骤1
你的新观点是
第2步
第3步
转换回原始旋转中心:
为了更深入的解释,有一些花哨的图表,我建议看看这个.
上面接受的答案对我来说不正确,旋转是相反的,这是工作功能
/*
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};
}
Run Code Online (Sandbox Code Playgroud)