不說廢話,直接上代碼,復制到項目改就完事了
wxml代碼文章來源:http://www.zghlxwxcb.cn/news/detail-714102.html
<!--index.wxml-->
<view class='wrapper'>
<view class="container">
<view class="title">雙指縮放圖片</view>
<scroll-view class='images' scroll-y="true" scroll-x="true" bindtouchmove="touchmoveCallback" bindtouchstart="touchstartCallback">
<image mode="aspectFit" src="https://image.91betterwei.com/maoshan/jingquMap.png" style="width:{{scaleWidth }}px;height:{{scaleHeight}}px" bindload="imgload"></image>
</scroll-view>
</view>
</view>
js代碼文章來源地址http://www.zghlxwxcb.cn/news/detail-714102.html
//index.js
Page({
/**
* 頁面的初始數(shù)據(jù)
*/
data: {
distance: 0, // 手指移動的距離
scale: 1, // 縮放比例
baseWidth: '', // 圖片實際寬度
baseHeight: '', // 圖片實際高度
initWidth: '', // 圖片默認顯示寬度
initHeight: '', // 圖片默認顯示高度
scaleWidth: '', // 圖片縮放后的寬度
scaleHeight: '', // 圖片縮放后的高度
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面加載
*/
onLoad: function (options) {
// 獲取屏幕寬度
this.width = wx.getSystemInfoSync().windowWidth;
},
/**
* 監(jiān)聽圖片加載成功時觸發(fā)
*/
imgload: function (e) {
this.multiple = e.detail.width / this.width; // 計算原圖和默認顯示的倍數(shù)
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,
})
},
/**
* 雙手指觸發(fā)開始 計算開始觸發(fā)兩個手指坐標的距離
*/
touchstartCallback: function (e) {
// 單手指縮放開始,不做任何處理
if (e.touches.length == 1) return;
let distance = this.calcDistance(e.touches[0], e.touches[1]);
this.setData({
'distance': distance,
})
},
/**
* 雙手指移動 計算兩個手指坐標和距離
*/
touchmoveCallback: function (e) {
// 單手指縮放不做任何操作
if (e.touches.length == 1) 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;
if (newScale >= this.multiple && this.multiple > 2) { // 原圖比較大情況
newScale = this.multiple;
} else if (this.multiple < 2 && newScale >= 2) { // 原圖較小情況
newScale = 2; // 最大2倍
};
// 最小縮放到1
if (newScale <= 1) {
newScale = 1;
};
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));
}
})
到了這里,關(guān)于微信小程序,圖片雙指放大縮小的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!