How to use atan2() in combination with other Radian angle systems

后端 未结 4 731
陌清茗
陌清茗 2021-02-04 18:46

I am struggling with this in JavaScript, but this problem applies to many other languages/environments as well.

I want to have one object rotating towards the position o

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 19:09

    Just use the condition

     var radians = Math.atan2(e.y - cy, e.x - cx);
     if(radians < 0 ) {radians += 2*Math.PI;}
    

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext("2d");
    canvas.onmousedown = function(e){
    var rect = canvas.getBoundingClientRect();
    var cx = rect.left + rect.width / 2, cy = rect.top + rect.height / 2;
    var radians = Math.atan2(e.y - cy, e.x - cx);
    if(radians < 0 ) {radians += 2*Math.PI;}
    ctx.moveTo(cx,cy);
    ctx.lineTo(cx + 100 * Math.cos(radians), cy + 100* Math.sin(radians));
    ctx.stroke();
    };

提交回复
热议问题