finding angles 0-360

前端 未结 10 1838
清酒与你
清酒与你 2020-12-25 15:16

Need help with a math issue: i need to get the true angle from 0 degrees using x and y cordinates im using this at the moment:

Math.atan((x2-x1)/(y1-y2))/(Ma         


        
10条回答
  •  佛祖请我去吃肉
    2020-12-25 16:03

    The answers of @jilles de wit and @jk. led me on the right path but for some reason did not provide the right solution for my problem that i think is very similar to the original question.

    I wanted to get up = 0°, right = 90°, down = 180°, left = 270° as in aeronautical navigation systems.

    Presuming the question was referring to canvas drawing i reached this solution:

    I first translated the canvas origin using ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2). I also halved e.offsetX and e.offsedY i got from a mouse event on the canvas to get x and y with the same coordinate system as the canvas.

    let radianAngle = Math.atan2(y, x);    // x has the range [-canvas.width/2 ... +canvas.width/2], y is similar
    let northUpAngle = radianAngle * 180 / PI + 90;    // convert to degrees and add 90 to shift the angle counterclockwise from it's default "left" = 0°
    if (x < 0 && y < 0) {    // check for the top left quadrant
        northUpAngle += 360;    // add 360 to convert the range of the quadrant from [-90...0] to [270...360] (actual ranges may vary due to the way atan2 handles quadrant boundaries)
    }
    northUpAngle.toFixed(2)    // to avoid getting 360° near the "up" position
    

    There might be a more concise solution using the modulo operation but i could't find it.

提交回复
热议问题