← Back to index

Circle ↔ line intersection

Drop a perpendicular from the circle centre to the line. If its length is ≤ r, the line intersects the circle; step ±√(r² - dist²) along the line direction to find the two points. Move the mouse to swing one end of the line.

See also: Perpendicular distance from a point to a line — how the foot is found; Reflect a line off a circle — same intersection problem solved as a quadratic in the ray parameter.

Pseudocode

foot = projection of c onto line a->b
dist = |c - foot|
if (dist > r) return []
k = sqrt(r*r - dist*dist)
dir = normalize(b - a)
return [foot + dir * k, foot - dir * k]

Source

const cx = 150, cy = 150, r = 70
const ax = 30, ay = 30
const bx = mouseX, by = mouseY

const dx = bx - ax, dy = by - ay
const lenSq = dx * dx + dy * dy
const t = ((cx - ax) * dx + (cy - ay) * dy) / lenSq
const footX = ax + dx * t
const footY = ay + dy * t

const distSq = (cx - footX) ** 2 + (cy - footY) ** 2
if (distSq <= r * r) {
    const k = Math.sqrt(r * r - distSq)
    const len = Math.sqrt(lenSq)
    const ux = dx / len, uy = dy / len
    const i1 = { x: footX + ux * k, y: footY + uy * k }
    const i2 = { x: footX - ux * k, y: footY - uy * k }
}