getClosestPointForLine static method

Offset getClosestPointForLine(
  1. Offset tap,
  2. Offset start,
  3. Offset end
)

Implementation

static Offset getClosestPointForLine(Offset tap, Offset start, Offset end) {
  // Calculate the shortest distance from the tap to the line segment
  double dx = end.dx - start.dx;
  double dy = end.dy - start.dy;

  // If the line is just a point
  if (dx == 0 && dy == 0) {
    return start;
  }

  // Calculate the parameter t
  double t =
      ((tap.dx - start.dx) * dx + (tap.dy - start.dy) * dy) /
      (dx * dx + dy * dy);

  // Clamp t to the range [0, 1]
  t = t.clamp(0.0, 1.0);

  // Find the closest point on the line segment
  Offset closestPoint = Offset(start.dx + t * dx, start.dy + t * dy);

  // Check the distance from the tap to the closest point
  return closestPoint;
}