How to calculate rotation in 2D in Javascript

前端 未结 5 1822
旧巷少年郎
旧巷少年郎 2020-12-07 17:07

I am not so familiar trigonometry, but I have only two points to rotate in 2D:

                    *nx, ny
               .     -
          .           -
            


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 17:24

    above accepted answer not work for me correctly, rotation are reversed , here is working function

    /*
     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};
     }
    

提交回复
热议问题