将Konva图层节点装入“视口”

问题描述 投票:2回答:1

我目前正在尝试创建一种算法,将视口置于舞台上的内容中心。

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"

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

我正在艰难地在脑海中以数学方式想象答案。我提出的唯一解决方案是从视图和舞台上的对象创建矩形,然后强制回答,以便视图的边缘不与舞台上的任何形状相交。

非常感谢任何指导

javascript canvas konvajs
1个回答
3
投票

您可以尝试使用以下内容:

// 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

© www.soinside.com 2019 - 2024. All rights reserved.