溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發布時間:2021-01-26 14:53:56 來源:億速云 閱讀:450 作者:小新 欄目:移動開發

這篇文章將為大家詳細講解有關微信小程序怎樣實現手指縮放圖片,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

用手指縮放圖片。其實在實現這個需求以前,并不知道,微信公眾號以及微信小程序里面有一個原生的api就自帶這個特效,而且微信朋友圈也是用的這個api。wx.previewImage,就是它。預覽圖片。除了不能預覽開發環境的本地電腦的圖片外,你手機真機的圖片,以及http服務器上的圖片都是可以預覽的,而且縮放功能做得很流暢。本文主要和大家介紹了微信小程序中實現手指縮放圖片的示例代碼。

先上源碼,然后在逐步剖析:

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>

寫到這里發現,就算小程序用不了這個js,我的ht5頁面也是可以用的,哈哈。

關于“微信小程序怎樣實現手指縮放圖片”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女