distancePointToSegment function

double distancePointToSegment(
  1. Offset point,
  2. Offset a,
  3. Offset b
)

Returns the shortest distance from point to the segment a-b.

Implementation

double distancePointToSegment(Offset point, Offset a, Offset b) {
  final ab = b - a;
  final ap = point - a;
  final abLen2 = ab.dx * ab.dx + ab.dy * ab.dy;
  if (abLen2 <= kEpsilonSquared) {
    return (point - a).distance;
  }
  var t = (ap.dx * ab.dx + ap.dy * ab.dy) / abLen2;
  if (t < 0) t = 0;
  if (t > 1) t = 1;
  final projection = Offset(a.dx + ab.dx * t, a.dy + ab.dy * t);
  return (point - projection).distance;
}