title: translate coordinates relative to line segment
body: <p>I need to write a function (in Javascript) that accepts the endpoints of a line segment and an additional point and returns coordinates for the point relative to the start point. So, based on this picture:</p>
  
  <p><a href="https://i.stack.imgur.com/TESQW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TESQW.png" alt="enter image description here"></a></p>
  
  <pre><code>function perpendicular_coords(x1,y1, x2,y2, xp,yp)
  </code></pre>
  
  <p>returns <code>[xp',yp']</code> where xp' is the distance from (xp,yp) along a line perpendicular to the line segment, and yp' is the distance from (x1,y1) to the point where that perpendicular line intersects the line segment.</p>
  
  <p>What I've tried so far:</p>
  
  <pre><code>function rotateRad(cx, cy, x, y, radians) {
      var cos = Math.cos(radians),
          sin = Math.sin(radians),
          nx = (cos * (x - cx)) + (sin * (y - cy)) + cx,
          ny = (cos * (y - cy)) - (sin * (x - cx)) + cy;
      return [nx, ny];
  }
  
  [xp', yp'] = rotateRad(x1,y1, xp, yp, Math.atan2(y2-y1,x2-x1));
  </code></pre>
  
  <p>I didn't write the function; got it from <a href="https://stackoverflow.com/a/17411276/1368860">https://stackoverflow.com/a/17411276/1368860</a></p>