translate coordinates relative to line segment
I got a good answer on StackOverflow: https://stackoverflow.com/questions/41701713/translate-coordinates-relative-to-line-segment/41702475#41702475 from https://stackoverflow.com/users/1579780/giladd:

function perpendicular_coords(x1, y1, x2, y2, xp, yp) {
  var dx = x2 - x1,
      dy = y2 - y1;

  //find intersection point    
  var k = (dy * (xp-x1) - dx * (yp-y1)) / (dy*dy + dx*dx);
  var x4 = xp - k * dy;
  var y4 = yp + k * dx;

  var ypt = Math.sqrt((y4-y1)*(y4-y1)+(x4-x1)*(x4-x1));
  var xpt = distance(x1, y1, x2, y2, xp, yp);
  return [xpt, ypt];
}

// Distance of point from line
function distance(x1, y1, x2, y2, xp, yp) {
  var dx = x2 - x1;
  var dy = y2 - y1;

  return Math.abs(dy*xp - dx*yp + x2*y1 - y2*x1) / Math.sqrt(dy*dy + dx*dx);
}