微信小程序實現通過雙向滑動縮放圖片大小的方法

這篇文章主要介紹了微信小程序實現通過雙向滑動縮放圖片大小的方法,結合實例形式分析了微信小程序事件響應及圖片元素屬性動態操作相關實現技巧,需要的朋友可以參考下

本文實例講述了微信小程序實現通過雙向滑動縮放圖片大小的方法。分享給大家供大家參考,具體如下:

在做小程序開發的過程中,後端傳來一張圖片地圖,需要實現雙手指滑動,使圖片縮放,最終得出了一下代碼:

js :

Page({
 data: {
  touch: {
   distance: 0,
   scale: 1,
   baseWidth: null,
   baseHeight: null,
   scaleWidth: null,
   scaleHeight: null
  }
 },
 touchStartHandle(e) {
 // 單手指縮放開始,也不做任何處理
 if (e.touches.length == 1) {
   console.log("單滑了")
 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,
  })
 },
 touchMoveHandle(e) {
  let touch = this.data.touch
 // 單手指縮放我們不做任何操作
 if (e.touches.length == 1) {
   console.log("單滑了");
 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
  })
 },
 load: 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:

<image mode='scaleToFill' src='../../../images/01.jpg'
bindtouchstart='touchStartHandle'
bindtouchmove='touchMoveHandle'
bindload='load'
style="width: {{ touch.scaleWidth }}px;
height: {{ touch.scaleHeight }}px"></image>

最後,通過手機預覽,就會發現已達到預想的效果!

希望本文所述對大家微信小程序開發有所幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章