# Calculate the angle of a line defined by two points

Use Math.atan2 for the angle from the x axis, in radians or degrees.

Canonical: https://1loc.dev/math/calculate-the-angle-of-a-line-defined-by-two-points/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Local fixtures; no external services
Updated: 2026-10-28

## Implementation

```javascript
function angle({ p1, p2, unit = 'radians' }) { const radians = Math.atan2(p2.y - p1.y, p2.x - p1.x); return unit === 'degrees' ? radians * 180 / Math.PI : radians; }
```

## Input

```json
{
  "p1": {
    "x": 0,
    "y": 0
  },
  "p2": {
    "x": 1,
    "y": 1
  },
  "unit": "degrees"
}
```

## Expected output

```json
45
```

## Edge case

Input:
```json
{
  "p1": {
    "x": 0,
    "y": 0
  },
  "p2": {
    "x": -1,
    "y": 0
  }
}
```
Output:
```json
3.141592653589793
```

## Limits

- atan2 handles every quadrant, unlike atan(dy / dx). The result is in (−π, π].
- In screen coordinates y grows downward, so angles turn clockwise.

The lab validates types and size before calling this function. Add equivalent validation at your own trust boundary.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/calculate-the-angle-of-a-line-defined-by-two-points.mdx
Source file (this edition): https://github.com/akamind/1loc/blob/0a77f131b22d2ba3b7ec1728846f900c22821678/contents/calculate-the-angle-of-a-line-defined-by-two-points.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Combines the radians and degrees variants behind a unit option. Original MDX retained as inert source evidence.
