Konvajs 滚动到层的中心

Konvajs scroll to the center of layer

我有点卡在这个问题上了。我想根据图层的中心而不是鼠标指针进行缩放。 这是我从 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();
    });

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

您只需要通过认为 "mouse pointer" 位于 canvas 的中心来更新该示例。它可以是这样的:

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