【问题标题】:Konvajs scroll to the center of layerKonvajs 滚动到图层的中心
【发布时间】:2020-09-01 18:03:44
【问题描述】:

我有点卡在这个问题上。我想根据图层的中心而不是鼠标指针进行缩放。 这是我从https://konvajs.org/docs/sandbox/Zooming_Relative_To_Pointer.html 得到的 Konva 演示 表格

state.stage.on('wheel', (e) => {
      e.evt.preventDefault();
      var oldScale = state.layer.scaleX();

      var pointer = state.layer.getPointerPosition();

      var mousePointTo = {
        x: 0,
        y: 0
      };

      var newScale =
        e.evt.deltaY > 0 ? oldScale * scaleBy : oldScale / scaleBy;

      stage.scale({ x: newScale, y: newScale });

      var newPos = {
        x:  newScale,
        y:  newScale,
      };
      state.layer.position(newPos);
      state.layer.batchDraw();
    });

我也想有办法让它回到原来的位置。

【问题讨论】:

    标签: scale layer konvajs


    【解决方案1】:

    您只需要通过认为“鼠标指针”位于画布的中心来更新该示例。可以是这样的:

    var scaleBy = 1.01;
    stage.on('wheel', (e) => {
      e.evt.preventDefault();
      var oldScale = stage.scaleX();
    
      var pointer = {
        x: stage.width() / 2,
        y: stage.height() / 2
      };
    
      var origin = {
        x: (pointer.x - stage.x()) / oldScale,
        y: (pointer.y - stage.y()) / oldScale,
      };
    
      var newScale =
          e.evt.deltaY > 0 ? oldScale * scaleBy : oldScale / scaleBy;
    
      stage.scale({ x: newScale, y: newScale });
    
      var newPos = {
        x: pointer.x - origin.x * newScale,
        y: pointer.y - origin.y * newScale,
      };
      stage.position(newPos);
      stage.batchDraw();
    });
    

    https://jsbin.com/jikuzutuse/2/edit?html,js,output

    【讨论】:

    • 这很好。但是,如何将其缩放回原始大小?例如,我已经缩小/缩小了很多,并希望鼠尾草及其所有元素恢复到原来的大小。
    • 使用var newScale = 1;
    • 这并没有达到我的预期。 state.stage.scale(1, 1); state.stage.position(1, 1); state.stage.batchDraw();它只是去了左上角,但没有回到缩放前的样子,你能给我发个小提琴吗
    • 演示?另外,应该是stage.scale({x: 1, y: 1});
    • 做到了!谢谢@lavrton。
    猜你喜欢
    • 1970-01-01
    • 2020-04-17
    • 2019-07-10
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    相关资源
    最近更新 更多