【问题标题】:Fitting Konva layer nodes into "viewport"将 Konva 层节点安装到“视口”中
【发布时间】:2018-03-01 23:09:12
【问题描述】:

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

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"

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

我很难在脑海中以数学方式可视化答案。我想出的唯一解决方案是从视图和舞台上的对象创建矩形并暴力破解答案,以便视图的边缘不会与舞台上的任何形状相交。

任何指导将不胜感激

【问题讨论】:

    标签: javascript canvas konvajs


    【解决方案1】:

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

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

    【讨论】:

    • 一个非常优雅的解决方案,非常感谢!我将不得不查看 layer.getClientRect({ relativeTo: stage }); 的源代码因为那是我肯定错过的关键。当视口更大时,我的下一步将是让元素在画布中居中。再次真诚感谢!
    • 嘿@lavtron 谢谢你的解决方案!虽然这将始终在画布内左对齐地图 - 有没有办法让它始终水平和垂直居中?非常感谢
    • @stillfire 应该很简单。稍微修正一下计算。
    猜你喜欢
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 2016-09-13
    相关资源
    最近更新 更多