欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

微信小程序中實(shí)現(xiàn)手指縮放圖片的示例代碼

 更新時(shí)間:2018年03月13日 10:00:30   作者:健兒  
本篇文章主要介紹了微信小程序中實(shí)現(xiàn)手指縮放圖片的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

公司開(kāi)發(fā)微信小程序,pm想實(shí)現(xiàn)如下需求:

用手指縮放圖片。其實(shí)在實(shí)現(xiàn)這個(gè)需求以前,并不知道,微信公眾號(hào)以及微信小程序里面有一個(gè)原生的api就自帶這個(gè)特效,而且微信朋友圈也是用的這個(gè)api。wx.previewImage,就是它。預(yù)覽圖片。除了不能預(yù)覽開(kāi)發(fā)環(huán)境的本地電腦的圖片外,你手機(jī)真機(jī)的圖片,以及http服務(wù)器上的圖片都是可以預(yù)覽的,而且縮放功能做得很流暢。下面就說(shuō)說(shuō)如何用js來(lái)實(shí)現(xiàn)這個(gè)功能吧。

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

Page({
  data: {
    touch: {
      distance: 0,
      scale: 1,
      baseWidth: null,
      baseHeight: null,
      scaleWidth: null,
      scaleHeight: null
    }
  },
  touchstartCallback: function(e) {
    // 單手指縮放開(kāi)始,也不做任何處理
    if(e.touches.length == 1) return
    console.log('雙手指觸發(fā)開(kāi)始')
    // 注意touchstartCallback 真正代碼的開(kāi)始
    // 一開(kāi)始我并沒(méi)有這個(gè)回調(diào)函數(shù),會(huì)出現(xiàn)縮小的時(shí)候有瞬間被放大過(guò)程的bug
    // 當(dāng)兩根手指放上去的時(shí)候,就將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('雙手指運(yùn)動(dòng)')
    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 這個(gè)api是<image>組件的api類(lèi)似<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文件對(duì)應(yīng)如下,就不做解釋了:

<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>

寫(xiě)到這里發(fā)現(xiàn),就算小程序用不了這個(gè)js,我的ht5頁(yè)面也是可以用的,哈哈。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論