Intersection of a line and a circle

Plain JavaScript source code

Introduction

Line ax + by + c = 0:

Line:

Circle with center (xm,ym) and radius r:

P1 =

P2 =

Fig.1. App to calculate the intersection points P1 and P2 of a line and a circle.

Given: line parameters a, b and c and circle center M = x m y m and circle radius r.

General linear equation with two variables:

a x + b y + c = 0

We can write this as an equation of a straight line like:

If b 0 : y = m x + y 0 If b = 0 : x = k with:
m = a b , y 0 = c b , k = c a

In case b ≠ 0, m is called the slope or gradient of the line and y0 is called the y-intercept. If b = 0, the line is a vertical line.

General circle equation:

x x m 2 + y y m 2 = r 2 x 2 2 x x m + x m 2 + y 2 2 y y m + y m 2 + r 2 = 0 [1]

If b ≠ 0:

Substituting line equation y = m x + y 0 in [1] results in an equation of the form:

A x 2 + B x + C = 0

This equation's solutions for x are the x-coordinates of the intersection points P = x p a b x p c b :

x p = B ± B 2 4 A C 2 A with: A = a 2 b 2 + 1 B = 2 a c b 2 x m + a b y m C = x m 2 + y m 2 + 2 c b y m + c 2 b 2 r 2

Let D = B 2 4 A C :

  • If D < 0, then x p has no solutions; line does not intersect.
  • If D = 0, then x p has exactly one solution; line is tangent to circle.
  • If D > 0, then x p has two solutions; line intersects at two points.

If b = 0:

Substituting vertical line equation x = k in [1] results in an equation of the form:

y 2 + B y + C = 0

This equation's solutions for y are the y-coordinates of the intersection points P = c a y p :

y p = B ± B 2 4 C 2 with: B = 2 y m C = x m 2 + y m 2 + 2 c a x m + c 2 a 2 r 2

Let D = B 2 4 C :

  • If D < 0, then y p has no solutions; line does not intersect.
  • If D = 0, then y p has exactly one solution; line is tangent to circle.
  • If D > 0, then y p has two solutions; line intersects at two points.