微信小程序中實現手指縮放圖片


上代碼

Page({
    data: {
        touch: {
            distance: 0,
            scale: 1,
            baseWidth: null,
            baseHeight: null,
            scaleWidth: null,
            scaleHeight: null
        }
    },
    touchstartCallback: function(e) {
        // 單手指縮放開始,也不做任何處理 if(e.touches.length == 1) return console.log('雙手指觸發開始')
        // 注意touchstartCallback 真正代碼的開始 // 一開始我並沒有這個回調函數,會出現縮小的時候有瞬間被放大過程的bug // 當兩根手指放上去的時候,就將distance 初始化。 let xMove = e.touches[1].clientX - e.touches[0].clientX;
        let yMove = e.touches[1].clientY - e.touches[0].clientY;
        let distance = Math.sqrt(xMove * xMove + yMove * yMove);
        this.setData({
           'touch.distance': distance,
        })
    },
    touchmoveCallback: function(e) {
        let touch = this.data.touch
        // 單手指縮放我們不做任何操作 if(e.touches.length == 1) return console.log('雙手指運動')
        let xMove = e.touches[1].clientX - e.touches[0].clientX;
        let yMove = e.touches[1].clientY - e.touches[0].clientY;
        // 新的 ditance let distance = Math.sqrt(xMove * xMove + yMove * yMove);
        let distanceDiff = distance - touch.distance;
        let newScale = touch.scale + 0.005 * distanceDiff
        // 為了防止縮放得太大,所以scale需要限制,同理最小值也是 if(newScale >= 2) {
            newScale = 2
        }
        if(newScale <= 0.6) {
            newScale = 0.6
        }
        let scaleWidth = newScale * touch.baseWidth
        let scaleHeight = newScale * touch.baseHeight
        // 賦值 新的 => 舊的 this.setData({
           'touch.distance': distance,
           'touch.scale': newScale,
           'touch.scaleWidth': scaleWidth,
           'touch.scaleHeight': scaleHeight,
           'touch.diff': distanceDiff
        })
    },
    bindload: function(e) {
      // bindload 這個api是<image>組件的api類似<img>的onload屬性 this.setData({
          'touch.baseWidth': e.detail.width,
          'touch.baseHeight': e.detail.height,
          'touch.scaleWidth': e.detail.width,
          'touch.scaleHeight': e.detail.height
      })
    }
})

WXML代碼如下

<view class="container">
    <view bindtouchmove="touchmoveCallback" bindtouchstart="touchstartCallback">
        <image src="../../resources/pic/cat.jpg" style="width: {{ touch.scaleWidth }}px;height: {{ touch.scaleHeight }}px" bindload="bindload"></image>
    </view>
</view>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM