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

该代码片段展示了如何在Vue3和TypeScript环境下,利用Konva库处理触屏事件,实现舞台的双指缩放和拖动功能。当两个触点同时移动时,计算舞台的缩放比例和新位置,阻止默认的拖动行为并自定义平移逻辑。
摘要由CSDN通过智能技术生成

使用了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)
  });
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值