Q:

Fit X-axis and scaleXY to keep canvas in center after zooming out

I would like to use Konva js to accomplish tasks below:
1- Loop data from db and then draw groups on canvas, group contains circle+text
2- When shapes increase, zooming out to keeping them in the middle
The challenge i encountered:

When shapes exceeds layer width i start zooming out but i can't keeping them in the middle.

How to calcul layer x-axis depend on shapes to keep canvas centred?
How can i calculate the zoom to keep place just for a new shape and not zooming out too much?
Thank you in advance
Please find the: codesandbox

A:

First of all, I have never used Konva before so maybe there are other solutions which simpler than this.
Use getClientRect bounding of stage compare to its width and height to find the right scale then translate its to center.
const adjustStage = function (stage) {
  let width = stage.width()
  let height = stage.height()
  let scaleX = stage.scaleX()
  let scaleY = stage.scaleY()
  let rect = stage.getClientRect()

  // calculate scale to fit stage on each axis then choose the small one
  let scale = Math.min(
    width / rect.width,
    height / rect.height
  )

  stage.scale({
    x: scaleX * scale,
    y: scaleY * scale
  })

  // get new scaled rect
  rect = stage.getClientRect()

  // calculate distance difference between two centers on each axis.
  stage.move({
    x: width / 2 - (rect.x + rect.width / 2),
    y: height / 2 - (rect.y + rect.height / 2)
  })

  stage.draw()
}

Result here

