Konva Transformer is not supporting two finger scaling and scaling is very difficult in mobile devices

419 views Asked by At

I used below code to initiate Transformer

const tr = new Konva.Transformer();

But the two finger scaling is not supporting and it's very difficult scale in mobile devices.

Anyone know how to fix this?

1

There are 1 answers

0
lavrton On BEST ANSWER

With konva v4 you have to implement multitouch scale manually:

const stage = new Konva.Stage({
  container: "container",
  width: window.innerWidth,
  height: window.innerHeight
});

const layer = new Konva.Layer();
stage.add(layer);

const shape = new Konva.Circle({
  x: stage.width() / 2,
  y: stage.height() / 2,
  radius: 200,
  fill: "green"
});
layer.add(shape);

const tr = new Konva.Transformer({
  node: shape
});
layer.add(tr);

function getDistance(touches) {
  const x1 = touches[0].clientX;
  const y1 = touches[0].clientY;
  const x2 = touches[1].clientX;
  const y2 = touches[1].clientY;
  return Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
}

let lastDist = 0;
shape.on("touchstart", e => {
  const touches = e.evt.touches;
  if (touches.length < 2) {
    return;
  }
  lastDist = getDistance(touches);
});

// listen stage events, so we we go outside of shape we still listen to changes
stage.on("touchmove", e => {
  const touches = e.evt.touches;
  if (touches.length < 2) {
    return;
  }
  if (!lastDist) {
    return;
  }
  const newDist = getDistance(touches);
  const scaleFactor = newDist / lastDist;
  const newScale = shape.scaleX() * scaleFactor;
  shape.scaleX(newScale);
  shape.scaleY(newScale);
  lastDist = newDist;
  layer.batchDraw();
});

stage.on("touchend", () => {
  lastDist = 0;
});

layer.draw();

Demo: https://codesandbox.io/s/heuristic-dirac-flvk7

Related demos: