前言微信小程序的一指拖动和两指操作是比较常见的功能,效果如下图实现这三个功能,主要是利用三个触摸事件touchstart,touchmove,touchend使用以下变量Page({data:{translateX:0,//位移x坐标单位pxtranslateY:0,//位移y坐标单位pxdistance:0,//两指触摸点距离scale:1,//缩放系数rotate:0,//旋转角度oldRotate:0,//上次旋转停止后的角度startMove:{//起始位移距离x:0,y:0,},startTouches:[]//起始点触摸数组},})单指单指拖放比较简单。只需要记录移动点的坐标,然后减去起点的坐标,就可以得到相对于页面的移动距离。touchstarttouchStart(e){consttouches=e.touchesconst{translateX,translateY}=this.dataconst{pageX,pageY}=touches[0]this.data.startMove={x:pageX-翻译lateX,y:pageY-translateY}this.data.startTouches=touches},touchmovetouchMove(e){consttouches=e.touchesconst{pageX:onePageX,pageY:onePageY}=touches[0]常量{startMove}=this.datathis.setData({translateX:onePageX-startMove.x,translateY:onePageY-startMove.y})}Pinchzoompinchzoom的原理是根据两点的坐标计算距离(勾股定理),然后使用移动坐标的距离比例可以计算缩放系数touchmovetouchMove(e){consttouches=e.touchesconst{pageX:onePageX,pageY:onePageY}=touches[0]const{startMove,scale,distance:oldDistance,startTouches}=this.dataif(touches.length===2&&startTouches.length===2){//双指缩放const{pageX:twoPageX,pageY:twoPageY}=touches[1]//求当前两指距离constdistance=Math.sqrt((twoPageX-onePageX)**2+(twoPageY-onePageY)**2)this.data.distance=distancethis.setData({scale:scale*(distance/(oldDistance||distance))})}elseif(startTouches.length!==2){//用一根手指拖动this.setData({translateX:onePageX-startMove.x,translateY:onePageY-startMove.y})}}startTouches.length!==2之所以这样判断是为了防止图片跳动,因为如果用两根手指触摸,然后留下一根手指,我禁止拖放。只有当双指离开再触摸时,才能实现一指拖动和两指旋转。减去最后一次旋转的角度等于你当前选择的角度:oldDistance,startTouches,oldRotate}=this.dataif(touches.length===2&&startTouches.length===2){const{pageX:twoPageX,pageY:twoPageY}=touches[1]constdistance=Math.sqrt((twoPageX-onePageX)**2+(twoPageY-onePageY)**2)+letrotate=this.getAngle(touches[0],touches[1])-this.getAngle(startTouches[0],startTouches[1])+oldRotate//如果大于degree,减去360+rotate=rotate>360?旋转-360:旋转this.data.distance=distancethis.setData({scale:scale*(distance/(oldDistance||distance)),+rotate})}elseif(startTouches.length!==2){this.setData({translateX:onePageX-startMove.x,translateY:onePageY-startMove.y})}},getAnglegetAngle(p1,p2){constx=p1.pageX-p2.pageXconsty=p1.pageY-p2.pageY返回数学.atan2(y,x)*180/Math.PI}touchendtouchEnd(){//保存当前旋转角度this.data.oldRotate=this.data.rotate},总结代码片段https://developers.weixin。qq。com/s/0nS1tImU7Rs5H5原理一样,只是改一下语法