raw math

Given a circle with it's center point MM, the radius rr and an angle α\alpha of the radius line, how can one calculate the tangent line on the circle in point TT? The trick is, that the radius line and the tangent line are perpendicular. This means, that their dot-product must be zero.

So, how can this schematic be derived? The intersection point TT is the center point MM plus the radius in the direction of the angle:

T=(TxTy)=M+r(sinαcosα)T = \left(\begin{array}{c} T_x\\ T_y \end{array}\right) = M + r \cdot \left(\begin{array}{c} \sin\alpha\\ \cos\alpha \end{array}\right)

Now we need to rotate the vector by 90° in order to get a vector that is perpendicular to the radius line:

v=(0110)MT\vec{v} = \left(\begin{array}{cc} 0 & 1\\ -1 & 0 \end{array}\right) \cdot \vec{MT}

Which leads to the line equation:

L(s)=T+svvL(s) = T + s \cdot \frac{\vec{v}}{|\vec{v}|}

The implementation is therefore also quite simple:

function tangentLine(M, r, alpha) {

   T = {
      x: M.x + Math.cos(alpha) * r,
      y: M.y + Math.sin(alpha) * r
   }

   v = {
      x: T.y - M.y,
      y: M.x - T.x
   }

   norm = Math.hypot(v.x, v.y)
   v.x/= norm
   v.y/= norm

   return [T, v]
}