多点触控手势怎么监听缩放操作?
我在移动端做图片查看器,想实现双指缩放,但 touchstart 和 touchmove 事件里拿到的 touches 长度有时候不对,缩放时经常触发两次甚至更多次处理,逻辑乱了。
我试过用两个 touch 点的距离计算缩放比例,但手指刚接触屏幕时 touches 数量变化太快,导致初始距离算错。下面是我写的部分代码:
let startDistance = 0;
function handleTouchStart(e) {
if (e.touches.length === 2) {
const dx = e.touches[0].pageX - e.touches[1].pageX;
const dy = e.touches[0].pageY - e.touches[1].pageY;
startDistance = Math.sqrt(dx * dx + dy * dy);
}
}
function handleTouchMove(e) {
if (e.touches.length === 2) {
// 这里有时拿不到正确的 startDistance
const dx = e.touches[0].pageX - e.touches[1].pageX;
const dy = e.touches[0].pageY - e.touches[1].pageY;
const currentDistance = Math.sqrt(dx * dx + dy * dy);
const scale = currentDistance / startDistance;
console.log('scale:', scale);
}
}
记得把三个事件都绑上,touchend 也要处理,不然 isScaling 状态会乱。凌晨三点调试这种问题确实让人头秃。