centerViewport method

void centerViewport()

Centers the viewport on the geometric center of all nodes without changing zoom.

Calculates the center point of all nodes in the graph and pans the viewport to that location while maintaining the current zoom level.

Does nothing if there are no nodes or if the screen size is zero.

This is useful for recentering your view on the content without losing your current zoom level, unlike fitToView which adjusts the zoom.

Example:

// User zoomed in to 200% and panned around
controller.setZoom(2.0);
// ... user pans around ...

// Recenter on all nodes while keeping 200% zoom
controller.centerViewport();

See also:

Implementation

void centerViewport() {
  if (_nodes.isEmpty || _screenSize.value == Size.zero) return;

  final bounds = nodesBounds;
  if (bounds == Rect.zero) return;

  // Get the center of all nodes
  final center = bounds.center;
  final currentVp = _viewport.value;

  setViewport(
    GraphViewport(
      x: _screenSize.value.width / 2 - center.dx * currentVp.zoom,
      y: _screenSize.value.height / 2 - center.dy * currentVp.zoom,
      zoom: currentVp.zoom,
    ),
  );
}