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

本文介绍如何使用Konva.js结合Vue3与TypeScript实现移动端双指触摸缩放功能。通过监听touchmove事件并计算两指间的距离变化来调整画布的缩放比例,同时更新画布位置以保持缩放焦点不变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用了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、付费专栏及课程。

余额充值