Bootstrap

使用knova实现在移动端双指放大或缩小的操作

使用了vue3+ts进行开发

const lastCenter = ref<{
  x: number
  y: number
} | null>(null)
const lastDist = ref(0)
stage.value?.on('touchmove', (e) => {
    e.evt.preventDefault();
    const touch1 = e.evt.touches[0];
    const touch2 = e.evt.touches[1];
    if (touch1 && touch2) {
      if (stage.value) {
      	// 在缩放过程中禁止拖动
        stage.value.draggable(false)
        // if the stage was under Konva's drag&drop
        // we need to stop it, and implement our own pan logic with two pointers
        if (stage.value.isDragging()) {
          stage.value.stopDrag();
        }
        const p1 = {
          x: touch1.clientX,
          y: touch1.clientY,
        };
        const p2 = {
          x: touch2.clientX,
          y: touch2.clientY,
        };
        if (!lastCenter.value) {
          lastCenter.value = getCenter(p1, p2);
          return;
        }
        const newCenter = getCenter(p1, p2);
        const dist = getDistance(p1, p2)
        if (!lastDist.value) {
          lastDist.value = dist;
        }
        const pointTo = {
          x: (newCenter.x - stage.value.x()) / stage.value.scaleX(),
          y: (newCenter.y - stage.value.y()) / stage.value.scaleX(),
        };
        const scale = stage.value.scaleX() * (dist / lastDist.value);
        stage.value.scaleX(scale);
        stage.value.scaleY(scale);
        // calculate new position of the stage
        const dx = newCenter.x - lastCenter.value.x;
        const dy = newCenter.y - lastCenter.value.y;
        const newPos = {
          x: newCenter.x - pointTo.x * scale + dx,
          y: newCenter.y - pointTo.y * scale + dy,
        };
        stage.value.position(newPos);
        lastDist.value = dist;
        lastCenter.value = newCenter;
      }
    }
  })
  stage.value?.on('touchend', function () {
    lastDist.value = 0;
    lastCenter.value = null;
    stage.value?.draggable(true)
  });
;