微信小程序单指、双指操作图片/层(移动缩放)
微信小程序单指、双指操作图片/层WXML:
<view class="myCanvas">
<image src="{{ loadSrc}}" class="img" bindtouchstart="touchstartCallback" bindtouchmove="touchmoveCallback" bindload="imgload" style="width: {{ scaleWidth }}px;height: {{ scaleHeight }}px;margin-top:{{marginTop}}px;margin-left:{{marginLeft}}px;" />
</view>
微信小程序单指、双指操作图片/层JS:
/**
* 监听图片加载成功时触发
*/
imgload: function (e) {
this.multiple = e.detail.width / this.width; // 计算原图和默认显示的倍数
let height = this.multiple > 1 ? e.detail.height / this.multiple : e.detail.height; // 等比例计算出默认高度
let width = this.multiple > 1 ? this.width : e.detail.width;
this.setData({
baseWidth: e.detail.width, // 获取图片实际宽度
baseHeight: e.detail.height, // 获取图片实际高度
initWidth: width,
initHeight: height,
scaleWidth: width,
scaleHeight: height,
})
},
/**
* 双手指触发开始 计算开始触发两个手指坐标的距离
*/
touchstartCallback: function (e) {
// 单手指缩放开始,不做任何处理
if (e.touches.length == 1) {
lastTouchPoint = { x: 0, y: 0 }
return
};
let distance = this.calcDistance(e.touches[0], e.touches[1]);
this.setData({
'distance': distance,
})
},
/**
* 双手指移动 计算两个手指坐标和距离
*/
touchmoveCallback: function (e) {
// 单手指缩放不做任何操作
if (e.touches.length == 1) {
if (lastTouchPoint.x == 0 && lastTouchPoint.y == 0) {
lastTouchPoint.x = e.touches[0].clientX
lastTouchPoint.y = e.touches[0].clientY
} else {
var xOffset = e.touches[0].clientX - lastTouchPoint.x
var yOffset = e.touches[0].clientY - lastTouchPoint.y
this.setData({
marginTop: this.data.marginTop + yOffset,
marginLeft: this.data.marginLeft + xOffset,
})
lastTouchPoint.x = e.touches[0].clientX
lastTouchPoint.y = e.touches[0].clientY
}
return
};
let distance = this.calcDistance(e.touches[0], e.touches[1]);
// 计算移动的过程中实际移动了多少的距离
let distanceDiff = distance - this.data.distance;
let newScale = this.data.scale + 0.005 * distanceDiff;
// 最小缩放到0.5
if (newScale <= 0.5) {
newScale = 0.5;
};
let scaleWidth = newScale * this.data.initWidth;
let scaleHeight = newScale * this.data.initHeight;
this.setData({
distance: distance,
scale: newScale,
scaleWidth: scaleWidth,
scaleHeight: scaleHeight,
diff: distanceDiff
});
},
/**
* 计算两个手指距离
*/
calcDistance(pos0, pos1) {
let xMove = pos1.clientX - pos0.clientX;
let yMove = pos1.clientY - pos0.clientY;
return (Math.sqrt(xMove * xMove + yMove * yMove));
},