clipLine method

List<double> clipLine(
  1. double startX,
  2. double startY,
  3. double stopX,
  4. double stopY,
  5. Node destination,
)

Implementation

List<double> clipLine(double startX, double startY, double stopX, double stopY, Node destination) {
  var resultLine = List.filled(4, 0.0);
  resultLine[0] = startX;
  resultLine[1] = startY;

  var slope = (startY - stopY) / (startX - stopX);
  var halfHeight = destination.height / 2;
  var halfWidth = destination.width / 2;
  var halfSlopeWidth = slope * halfWidth;
  var halfSlopeHeight = halfHeight / slope;

  if (-halfHeight <= halfSlopeWidth && halfSlopeWidth <= halfHeight) {
    // line intersects with ...
    if (destination.x > startX) {
      // left edge
      resultLine[2] = stopX - halfWidth;
      resultLine[3] = stopY - halfSlopeWidth;
    } else if (destination.x < startX) {
      // right edge
      resultLine[2] = stopX + halfWidth;
      resultLine[3] = stopY + halfSlopeWidth;
    }
  }

  if (-halfWidth <= halfSlopeHeight && halfSlopeHeight <= halfWidth) {
    // line intersects with ...
    if (destination.y < startY) {
      // bottom edge
      resultLine[2] = stopX + halfSlopeHeight;
      resultLine[3] = stopY + halfHeight;
    } else if (destination.y > startY) {
      // top edge
      resultLine[2] = stopX - halfSlopeHeight;
      resultLine[3] = stopY - halfHeight;
    }
  }

  return resultLine;
}