Math.atan2()
Math.atan2() 靜態方法返回平面上 (以弧度為單位) 從正 x 軸到點 (x, y) 的射線之間的角度,對於 Math.atan2(y, x)。
試一試
function calcAngleDegrees(x, y) {
return (Math.atan2(y, x) * 180) / Math.PI;
}
console.log(calcAngleDegrees(5, 5));
// Expected output: 45
console.log(calcAngleDegrees(10, 10));
// Expected output: 45
console.log(calcAngleDegrees(0, 10));
// Expected output: 90
語法
js
Math.atan2(y, x)
引數
返回值
弧度值 (包含 -π 和 π 之間) 從正 x 軸到點 (x, y) 的射線之間的角度。
描述
Math.atan2() 方法測量從正 x 軸到點 (x, y) 的逆時針角度 θ (以弧度為單位)。請注意,此函式的引數先傳遞 y 座標,後傳遞 x 座標。

Math.atan2() 接收獨立的 x 和 y 引數,而 Math.atan() 接收這兩個引數的比值。Math.atan2(y, x) 在以下情況下與 Math.atan(y / x) 不同:
x |
y |
Math.atan2(y, x) |
Math.atan(y / x) |
|---|---|---|---|
Infinity |
Infinity |
π / 4 | NaN |
Infinity |
-Infinity |
-π / 4 | NaN |
-Infinity |
Infinity |
3π / 4 | NaN |
-Infinity |
-Infinity |
-3π / 4 | NaN |
| 0 | 0 | 0 | NaN |
| 0 | -0 | -0 | NaN |
< 0 (包括 -0) |
0 | π | 0 |
< 0 (包括 -0) |
-0 | -π | 0 |
-Infinity |
> 0 | π | -0 |
| -0 | > 0 | π / 2 | -π / 2 |
-Infinity |
< 0 | -π | 0 |
| -0 | < 0 | -π / 2 | π / 2 |
此外,對於第二和第三象限的點 (x < 0),Math.atan2() 將輸出小於或大於.
由於 atan2() 是 Math 的靜態方法,您總是使用 Math.atan2() 來呼叫它,而不是透過您建立的 Math 物件的方法來呼叫 (Math 不是一個建構函式)。
示例
使用 Math.atan2()
js
Math.atan2(90, 15); // 1.4056476493802699
Math.atan2(15, 90); // 0.16514867741462683
Math.atan2(y, x) 和 Math.atan(y / x) 之間的區別
以下指令碼會打印出所有導致 Math.atan2(y, x) 和 Math.atan(y / x) 之間產生差異的輸入。
js
const formattedNumbers = new Map([
[-Math.PI, "-π"],
[(-3 * Math.PI) / 4, "-3π/4"],
[-Math.PI / 2, "-π/2"],
[-Math.PI / 4, "-π/4"],
[Math.PI / 4, "π/4"],
[Math.PI / 2, "π/2"],
[(3 * Math.PI) / 4, "3π/4"],
[Math.PI, "π"],
[-Infinity, "-∞"],
[Infinity, "∞"],
]);
function format(template, ...args) {
return String.raw(
{ raw: template },
...args.map((num) =>
(Object.is(num, -0)
? "-0"
: (formattedNumbers.get(num) ?? String(num))
).padEnd(5),
),
);
}
console.log(`| x | y | atan2 | atan |
|-------|-------|-------|-------|`);
for (const x of [-Infinity, -1, -0, 0, 1, Infinity]) {
for (const y of [-Infinity, -1, -0, 0, 1, Infinity]) {
const atan2 = Math.atan2(y, x);
const atan = Math.atan(y / x);
if (!Object.is(atan2, atan)) {
console.log(format`| ${x} | ${y} | ${atan2} | ${atan} |`);
}
}
}
輸出為:
| x | y | atan2 | atan | |-------|-------|-------|-------| | -∞ | -∞ | -3π/4 | NaN | | -∞ | -1 | -π | 0 | | -∞ | -0 | -π | 0 | | -∞ | 0 | π | -0 | | -∞ | 1 | π | -0 | | -∞ | ∞ | 3π/4 | NaN | | -1 | -∞ | -π/2 | π/2 | | -1 | -1 | -3π/4 | π/4 | | -1 | -0 | -π | 0 | | -1 | 0 | π | -0 | | -1 | 1 | 3π/4 | -π/4 | | -1 | ∞ | π/2 | -π/2 | | -0 | -∞ | -π/2 | π/2 | | -0 | -1 | -π/2 | π/2 | | -0 | -0 | -π | NaN | | -0 | 0 | π | NaN | | -0 | 1 | π/2 | -π/2 | | -0 | ∞ | π/2 | -π/2 | | 0 | -0 | -0 | NaN | | 0 | 0 | 0 | NaN | | ∞ | -∞ | -π/4 | NaN | | ∞ | ∞ | π/4 | NaN |
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-math.atan2 |
瀏覽器相容性
載入中…