code: function closePoint(px, py, ax, ay, bx, by, r) {
  
      var x = ax,
          y = ay,
          dx = bx - x,
          dy = by - y;
  
      if (dx !== 0 || dy !== 0) {
  
          var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
  
          if (t >= 1) {
              x = bx;
              y = by;
              t = 1;
  
          } else if (t > 0) {
              x += dx * t;
              y += dy * t;
  
          } else {
              t = 0;
          }
      }
  
      dx = px - x;
      dy = py - y;
  
      return dx * dx + dy * dy < r * r ? t : null;
  }
docs: find a closest point from a given point p to a segment [a, b] if it's within given square distance r