← Back to index

Rotate a point around a pivot

The standard 2D rotation: subtract the pivot, multiply by the rotation matrix, add the pivot back. Mouse position defines the target angle (measured from the pivot). The black point is the original; the red point is rotated to match the mouse angle.

See also: Axis-aligned bounding box — rotates a whole polygon using this same matrix.

Pseudocode

// Rotate point p around pivot by angle θ
dx = p.x - pivot.x
dy = p.y - pivot.y
p'.x = pivot.x + dx * cos(θ) - dy * sin(θ)
p'.y = pivot.y + dx * sin(θ) + dy * cos(θ)

Source

const pivotX = 150, pivotY = 150
const px = 250, py = 150       // original point, 100px to the right of the pivot

const theta = Math.atan2(mouseY - pivotY, mouseX - pivotX)
const cos = Math.cos(theta)
const sin = Math.sin(theta)

const dx = px - pivotX
const dy = py - pivotY
const rx = pivotX + dx * cos - dy * sin
const ry = pivotY + dx * sin + dy * cos