紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS Math.atan2 用法:座標轉角度

JS Math.atan2 用法:座標轉角度 特色圖片

Math.atan2() 是 JavaScript 由座標計算角度的靜態方法:傳入點的 y 與 x 座標,回傳「正 x 軸」到「原點 (0, 0) 指向該點的射線」之間的角度,單位是弧度(radian)。

白話一點,給一個點的位置,它告訴你這個點在原點的哪個方向。

語法

Math.atan2(y, x)
  • y:點的 y 座標。
  • x:點的 x 座標。
  • 回傳值:介於 -π 與 π(含)之間的弧度。

參數順序是 y 在前、x 在後,和一般寫座標 (x, y) 的順序相反,這是最常寫錯的地方。角度是從正 x 軸起算的逆時針方向。

基本用法

console.log(Math.atan2(90, 15)); // 1.4056476493802699
console.log(Math.atan2(15, 90)); // 0.16514867741462683

兩行只是把 y 與 x 對調,結果完全不同。

四個象限的結果

用「弧度轉角度」的小函式,看看不同位置的點得到的角度。注意函式的參數順序是 (x, y),內部才改成 Math.atan2(y, x):

function calcAngleDegrees(x, y) {
  return (Math.atan2(y, x) * 180) / Math.PI;
}

console.log(calcAngleDegrees(5, 5));   // 45
console.log(calcAngleDegrees(10, 10)); // 45
console.log(calcAngleDegrees(0, 10));  // 90
console.log(calcAngleDegrees(-5, 5));  // 135
console.log(calcAngleDegrees(-5, -5)); // -135
console.log(calcAngleDegrees(5, -5));  // -45
console.log(calcAngleDegrees(-1, 0));  // 180

整理成表格:

點 (x, y)所在位置角度
(5, 5)第一象限45 度
(-5, 5)第二象限135 度
(-5, -5)第三象限-135 度
(5, -5)第四象限-45 度
(-1, 0)負 x 軸180 度

第三、第四象限的結果是負值,因為範圍是 -π 到 π(-180 到 180 度)。

換成 0 到 360 度

需要 0 到 360 度時,把負的角度加上 360:

const toDegrees360 = (x, y) => ((Math.atan2(y, x) * 180) / Math.PI + 360) % 360;

console.log(toDegrees360(5, -5));  // 315
console.log(toDegrees360(-5, -5)); // 225
console.log(toDegrees360(5, 5));   // 45

兩點之間的角度

兩個點 a、b 之間的方向,用 b 減去 a 得到相對位置再傳進去:

const a = { x: 100, y: 100 };
const b = { x: 200, y: 50 };

const radians = Math.atan2(b.y - a.y, b.x - a.x);
console.log(radians);                    // -0.4636476090008061
console.log((radians * 180) / Math.PI);  // -26.56505117707799

與 Math.atan(y / x) 的差別

Math.atan() 只吃一個比值,Math.atan2() 則分別接收 y 與 x,所以不會因為相除而失去正負號。MDN 整理了兩者結果不同的情況,下表節錄其中幾列:

xyMath.atan2(y, x)Math.atan(y / x)
InfinityInfinityπ / 4NaN
000NaN
-Infinity-Infinity-3π / 4NaN
-0大於 0π / 2-π / 2

另外,第二、第三象限(x < 0)的點,Math.atan2() 會回傳小於 -π/2 或大於 π/2 的角度,Math.atan(y / x) 的範圍只有 -π/2 到 π/2,做不到。

console.log(Math.atan2(0, 0));         // 0
console.log(Math.atan(0 / 0));         // NaN
console.log(Math.atan2(Infinity, Infinity) === Math.PI / 4); // true
console.log(Math.atan2(-Infinity, -Infinity)); // -2.356194490192345
console.log(Math.atan(-Infinity / -Infinity)); // NaN

注意事項

  1. 參數順序是 (y, x):傳反了不會報錯,只會得到另一個角度。
  2. 範圍是 -π 到 π:需要 0 到 2π 或 0 到 360 度時,自行換算。
  3. 結果單位是弧度:顯示成度數時乘上 180 / Math.PI。
  4. 精度依引擎而異:MDN 說明 Math 的許多函式精度依實作而異,不同環境的結果最後幾位可能不同。

補充說明:範例輸出為 Node.js v22.20.0 的執行結果。只有一個比值要換算角度時,可用 Math.atan()。

參考資料與延伸閱讀

發佈留言