title: How to calculate intersection point of a line on a circle using p5.js
body: <p>I have a line (<code>se</code>) that I know starts inside a circle, and I know ends outside of a circle. I'm trying to find a point <code>l</code> where the line crosses the circle. </p>
  
  <p><a href="https://i.stack.imgur.com/SzFTD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SzFTD.png" alt="Calculate intersection point of a line in a circle – setup"></a></p>
  
  <p>I'm using the <a href="https://p5js.org/" rel="noreferrer">p5.js</a> library and have access to all of its Vector functions.</p>
  
  <p>My thoughts were, that if I can make a right angle on the line, to the radius, I can start solving some things.</p>
  
  <p><a href="https://i.stack.imgur.com/PYiRR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PYiRR.png" alt="Calculate intersection point of a line in a circle – attempt"></a></p>
  
  <pre><code>// Get the vector between s and c
  let scVector = p5.Vector.sub(start, circleCenter);
  // Get the angle between se and sc
  let escAngle = this.v.angleBetween(scVector);
  // Get the distance between t (where the right angle hits the center of the circle) and c
  let tcDistance = Math.sin(escAngle) * scVector.mag();
  // Get the distance between t and where the line intersects the circle
  let tlDistance = Math.sqrt(Math.pow(hole.r, 2) - Math.pow(tcDistance, 2));
  // Get the distance between the start point and t
  let stDistance = Math.sqrt(Math.pow(scVector.mag(), 2) - Math.pow(tcDistance, 2));
  // Add the two distances together, giving me the distance between s and l
  let totalDistance = tcDistance + stDistance;
  // Create a new Vector at this angle, at the totalDistance Magnitude, then add it to the current position
  let point = p5.Vector.fromAngle(this.v.heading(), totalDistance).add(start);
  // Mark a point (hopefully l) on the edge of the circle.
  points.push({
    x: point.x,
    y: point.y,
    fill: '#ffffff'
  })
  </code></pre>
  
  <p>Unfortunately, as my objects pass through the circle, they aren't leaving dots on the edge, but further away from the circle's edge.</p>
  
  <p><a href="https://i.stack.imgur.com/xMScH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xMScH.png" alt="enter image description here"></a></p>
  
  <p>The tiny dots are the marked positions, the coloured dots are the objects (which have a start and end point)</p>
  
  <p>I have a demo here, the questionable bit is line 42 onwards:
  <a href="https://codepen.io/EightArmsHQ/pen/be0461014f9868e3462868776d9c8f1a" rel="noreferrer">https://codepen.io/EightArmsHQ/pen/be0461014f9868e3462868776d9c8f1a</a></p>
  
  <p>Any help would be much appreciated.</p>