cameraOffset function

Offset cameraOffset({
  1. required Size screen,
  2. required Offset toward,
  3. required double zoom,
})

Where a camera has to move to zoom in on a point.

The scene's imposed transforms scale a node about its centre, so a point p lands at c + (p − c)·z and bringing it back to the centre is a translation of −(p − c)·z. Clamped so the screen's edge never comes inside the frame: a push-in that shows the backdrop past the app's corner is a camera that overshot, not a camera that zoomed.

Implementation

Offset cameraOffset({
  required Size screen,
  required Offset toward,
  required double zoom,
}) {
  var centre = screen.center(Offset.zero);
  var shift = (toward - centre) * -zoom;
  var slackX = (zoom - 1) * screen.width / 2;
  var slackY = (zoom - 1) * screen.height / 2;
  return Offset(
    shift.dx.clamp(-math.max(slackX, 0), math.max(slackX, 0)).toDouble(),
    shift.dy.clamp(-math.max(slackY, 0), math.max(slackY, 0)).toDouble(),
  );
}