title: Find new coordinates of point on line in javascript
body: <p>Let's say I have two points which I know: x1,y1 and x2,y2. I know I can easily calculate the length of this line with Pythagorean, but what if I want to calculate a shortened version of the line. For example, I would like the x,y coordinates 10 pixels toward the next point. Is there a simple formula for finding any new point on an angled line?</p>
  
  <hr>
  
  <p>OK, here is the solution as a JavaScript function. I've intentionally made this extra verbose for explanatory purposes. As the comments below suggested, you have to find the angle first, then calculate the sides with a new hypotenuse. </p>
  
  <p><img src="https://i.stack.imgur.com/dDxPj.gif" alt="Description of sides of triangle"></p>
  
  <pre><code>/**
   *  Calculates length of a line on Cartesian grid, then returns point that is X number of pixels down the line.
   *
   * @param  {Number} fromX - starting x point
   * @param  {Number} fromY - starting y point
   * @param  {Number} toX - ending x point for vector
   * @param  {Number} toY - ending y point for vector
   * @param  {Number} pxDistance - Number of pixels down line toward ending point to return
   * @return {Object} Returns x/y coords of point on line based on number of pixels given
   */ 
  function stortenLineDistance(fromX, fromY, toX, toY, pxDistance){
  
      //if line is vertical
      if(fromX === toX)
          return {x: toX, y: toY &gt; fromY ? fromY + pxDistance : fromY - pxDistance};
  
      //if line is horizontal
      if(fromY === toY)
          return {y: toY, x: toX &gt; fromX ? fromX + pxDistance : fromX - pxDistance};
  
      //get each side of original triangle length
      var adjacent   = toY - fromY;
      var opposite   = toX - fromX;
      var hypotenuse = Math.sqrt(Math.pow(opposite, 2) + Math.pow(adjacent,2));
  
      //find the angle
      var angle = Math.acos(adjacent/hypotenuse);
  
      //calculate new opposite and adjacent sides
      var newOpposite = Math.sin(angle) * pxDistance;
      var newAdjacent = Math.cos(angle) * pxDistance;
  
      //calculate new x/y, see which direction it's going
      var y = fromY - newAdjacent,
          x = fromX + newOpposite;
  
      return {y: y, x: x};
  
  }
  </code></pre>
  
  <p>EDIT: Wow, Stackoverflow is brutal. Feel free to delete this question if you wish, though I think it could be helpful to someone stuck on the same issue down the line. Maybe I'm wrong.</p>
  
  <p>At any rate, thanks to commenters for help.</p>