【问题标题】:Konvajs layer positions not being set as expectedKonvajs 图层位置未按预期设置
【发布时间】:2018-05-16 00:39:46
【问题描述】:

我有一个应用程序可以平移和缩放多个图层。

但是,当我设置图层的位置时,它们被更新为错误的值。

例如调用后:

layer.position({
    x: 12,
    y: 233,
});

我希望

layer.getClientRect();

返回

{
  x: 12,
  y: 233,
}

而是返回

{
  x: -22,
  y: 220,
}

发生这种情况是否有任何已知原因?

【问题讨论】:

    标签: konvajs


    【解决方案1】:

    似乎对我有用,正如这个缩减测试中所宣传的那样。你搬了舞台还是什么的?

    在下面的 sn-p 中,我绘制了一个具有 4 个“角”矩形的层,在“Layer pos #1”中显示其值(0, 0),然后将舞台移动到 12, 233并在显示 (12, 233) 的“Layer pos #2”中显示来自 grtClientRect() 的值。之后我将图层移回 (12, 23) 只是为了好玩。

    var stage = new Konva.Stage({
          container: 'container',
          width: 1600,
          height: 400
        });
    
    // add a layer
    var layer = new Konva.Layer();
    stage.add(layer);
    
    // add 4 corner rects - code I happened to have to hand
    var rectCorner = [];
    for (i=0;i<4;i=i+1){
      rectCorner[i] = new Konva.Rect({
            x: 0,
            y: 0,
            width: 50,
            height: 50,
            fill: 'red',
            opacity: 0.5,
            strokeWidth: 0})
        layer.add(rectCorner[i]);  
    }
    
    // put the rects in the corners to give a known layer space
    rectCorner[1].position({x:500, y: 0});
    rectCorner[2].position({x:500, y: 150});
    rectCorner[3].position({x:0, y: 150});
    layer.draw();
    
    // get the client rect now
    var p = layer.getClientRect();
    $('#info1').html('Layer pos #1=' + p.x + ', ' + p.y);
    
    // move the layer...
    layer.position({
        x: 12,
        y: 233,
    });
    
    // get the client rect now
    var p = layer.getClientRect();
    $('#info2').html('Layer pos #2=' + p.x + ', ' + p.y);
    
    // move the layer back to the top...
    layer.position({
        x: 12,
        y: 23,
    });
    
    stage.draw();
    p
    {
      padding: 4px;
      
    }
    #container
    {
      background-color: silver;
      overflow: hidden; 
    }
    <div id='info1'></div>
    <div id='info2'></div>
    
      <div id="container"></div>
                
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
        <script type="text/javascript" src="test.js"></script>

    【讨论】:

    • 嗨,征服袋熊。感谢那。我一直在挖掘并找出我哪里出错了。我已将其发布为答案。
    【解决方案2】:

    我意识到我没有考虑所有的偏移量。圆的 x 位置从中心设置,而getClientRect() 返回包括负数的宽度和高度。所以getClientRect() 在半径为 50 且 x 为 0 的圆上实际上会返回 {x: -25, y: -25, width: 50, height: 50}。

    【讨论】:

    • 另一点要考虑的是层大小和位置是如何运作的。 AFAIK(有空间确认这一点)层位置是围绕层上所有形状的最小边界框 - 将形状移到框外并改变层位置。可能出乎意料。
    猜你喜欢
    • 2018-02-24
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2018-09-12
    • 1970-01-01
    相关资源
    最近更新 更多