how to attach both rotate and tap event listeners to shapes in konvajs?

845 views Asked by At

I was working on including rotate gestures in my app following the tutorial given on https://konvajs.org/docs/sandbox/Gestures.html. But in my app i have also attached 'tap' event listener so whenever I tried to rotate the shape using gesture , 'tap' event gets emitted also and on taping the shape for once 'tap' event is getting emitted twice. Is there any way so that I can prevent that from happening means while rotation via 2 finger rotate gesture, 'tap' event should not get emitted? is there any way to use stopImmediatePropagation() in konvajs?

  group.on('tap', function(ev) {
    console.log("tap event")
  });

  group.on('rotatestart', function(ev) {
    oldRotation = ev.evt.gesture.rotation;
    startScale = rect.scaleX();
    group.stopDrag();
    group.draggable(false);
    text.text('rotating...');
  });

  group.on('rotate', function(ev) {
    var delta = oldRotation - ev.evt.gesture.rotation;
    group.rotate(-delta);
    oldRotation = ev.evt.gesture.rotation;
    group.scaleX(startScale * ev.evt.gesture.scale);
    group.scaleY(startScale * ev.evt.gesture.scale);
    layer.batchDraw();
  });

  group.on('rotateend rotatecancel', function(ev) {
    text.text(defaultText);
    group.draggable(true);
    layer.batchDraw();
  });

https://jsfiddle.net/pudio/z68nc5p3/2/

1

There are 1 answers

2
lavrton On

tap event is "native" konva event. It means Konva supports it by default. So Konva knows nothing about rotate events. Even if you are rotation a shape, for konva it still looks like you are tapping on it (it has touchdown and touchmove events).

But hammerjs handle such situations automatically. So instead of listening events on Konva node, you can listen to them on Hammertime instance:

hammertime.on('tap', function(ev) {
  console.log("tap event")
});

Demo: https://jsfiddle.net/hj84aLys/

That also will partially fix the double tap trigger issue, mentioned in the comments.

Another workaround is just check in tap event if rotate is happened resently. If it is not - then you can continue:

var rotated = false;
group.on('touchstart', function(ev) {
  rotated = false;
});

group.on('rotate', function(ev) {
  rotated = true;
});

group.on('tap', function(ev) {
  // do nothing on rotate.
  if (rotated) {
     return;
  }
  console.log("tap event")
});