移动端捏合缩放手势缩放比例计算不准怎么办?
在移动端实现图片捏合缩放时,我按照教程用touchstart和touchend事件计算两点距离,但缩放比例总忽大忽小,而且图片位置会偏移。我试过保存初始距离和当前距离差值,但效果还是不连贯:
let startDistance;
function handleStart(e) {
if(e.touches.length === 2) {
startDistance = getDistance(e.touches[0], e.touches[1]);
}
}
function handleMove(e) {
if(!startDistance || e.touches.length !== 2) return;
const currentDistance = getDistance(e.touches[0], e.touches[1]);
const scale = currentDistance / startDistance;
image.style.transform = <code>scale(${scale})</code>;
}
function getDistance(touch1, touch2) {
const dx = touch1.clientX - touch2.clientX;
const dy = touch1.clientY - touch2.clientY;
return Math.sqrt(dx*dx + dy*dy);
}
但测试时发现缩放基准点不对,而且快速捏合时会有跳跃感,这是坐标计算漏了什么关键步骤吗?
下面是修复后的代码,复制这个:
补充说明几点:
1.
transformOrigin设置缩放中心点,不设置的话默认是左上角2.
translate是为了补偿缩放引起的位移偏移3.
offsetLeft和offsetTop用来计算图片当前的偏移位置这样处理之后,缩放会以两指中心点为基准,并且位置偏移也会被补偿回来。测试的时候可以再加个
touchend重置变量,方便下一次缩放。1. 缩放基准点要取两指中心点,transform-origin 没设置当然跑偏了
2. 快速滑动跳跃是因为没做增量计算,scale 应该基于上一次的缩放值
改法如下: