Measure the container and choose a scale
Use the game container’s dimensions rather than assuming the window is the playable area. A ResizeObserver can report when that element changes, including changes caused by surrounding layout rather than a viewport resize. Decide whether the game should letterbox, crop or reflow at a narrow aspect ratio, and make the choice visible instead of stretching circles into ovals.
For a fixed virtual playfield, calculate one scale factor that fits its width and height, then center the remaining space. Convert pointer coordinates through the inverse of that same transform before hit testing. For a reflowing game, update layout anchors and collision shapes together so controls do not continue using positions from the previous size.
Keep resizing out of the simulation loop
Store the game world in stable units and treat canvas backing resolution, CSS size and device pixel ratio as rendering concerns. When size changes, update the drawing surface and redraw; do not reset the level or recompute object state unless the game rules require it. This separation prevents a toolbar resize from looking like a restart.
Test a narrow and wide viewport, a desktop resize and orientation change while the game is active. Check text wrapping, touch target positions and coordinate conversion. MDN’s ResizeObserver guide explains observing element dimensions and warns that changing the observed size inside the callback can create loops.
Questions about responsive game layouts
Should I resize the game world when the canvas changes size?
Usually keep simulation coordinates stable and adapt the presentation or layout. If the design intentionally changes the playfield, update its rules, objects and input mapping together.
Why use ResizeObserver instead of only window resize?
A game container can change size because of surrounding layout without a window resize. ResizeObserver reports element dimension changes directly.