将 Konva 层节点拟合到 "viewport"

Fitting Konva layer nodes into "viewport"

我目前正在尝试创建一种算法,使视口以舞台上显示的内容为中心。

Lets say the stage is initiated and it looks like this

I can get it to this point where the stage is centred over all shapes on the stage

Now I need a way to figure out how far to zoom the stage so that none of the shapes are cut off by the "viewport"

获得关于地图上每个形状的 origin/most 中心点是直截了当的,我可以做到那么远。我无法找到适当的计算来缩放舞台,使舞台上的每个形状都可见(加上一些额外的填充)

我真的很难在脑海中想象出一个数学答案。我想出的唯一解决方案是从视图和舞台上的对象创建矩形,然后暴力破解一个答案,这样视图的边缘就不会与舞台上的任何形状相交。

任何指导将不胜感激

你可以尝试使用这样的东西:

// do we need padding?
const padding = 10;

// get bounding rectangle
const box = layer.getClientRect({ relativeTo: stage });
const scale = Math.min(
  stage.width() / (box.width + padding * 2),
  stage.height() / (box.height + padding * 2)
);


stage.setAttrs({
  x: -box.x * scale + padding * scale,
  y: -box.y * scale  + padding * scale,
  scaleX: scale,
  scaleY: scale
});

http://jsbin.com/kobilamoro/2/edit?js,output