codernoob8
codernoob8

Reputation: 712

Konvajs scroll to the center of layer

I'm a little stuck on this problem. I would like to scale based on the center of the layer rather than a mouse pointer. Heres the Konva demo I got this from https://konvajs.org/docs/sandbox/Zooming_Relative_To_Pointer.html form

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();
    });

Also I want to have a way to have it go back to its original position.

Upvotes: 1

Views: 717

Answers (1)

lavrton
lavrton

Reputation: 20288

You just need to update that example by thinking that "mouse pointer" is at the center of the canvas. It can be something like this:

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

Upvotes: 1

Related Questions