首頁  >  文章  >  微信小程式  >  微信小程式實現手指縮放圖片程式碼分享

微信小程式實現手指縮放圖片程式碼分享

小云云
小云云原創
2018-03-14 09:10:352265瀏覽

用手指縮放圖片。其實在實現這個需求以前,並不知道,微信公眾號以及微信小程式裡面有一個原生的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({
      &#39;touch.distance&#39;: distance,
      &#39;touch.scale&#39;: newScale,
      &#39;touch.scaleWidth&#39;: scaleWidth,
      &#39;touch.scaleHeight&#39;: scaleHeight,
      &#39;touch.diff&#39;: distanceDiff
    })
  },
  bindload: function(e) {
   // bindload 这个api是<image>组件的api类似<img>的onload属性
   this.setData({
     &#39;touch.baseWidth&#39;: e.detail.width,
     &#39;touch.baseHeight&#39;: e.detail.height,
     &#39;touch.scaleWidth&#39;: e.detail.width,
     &#39;touch.scaleHeight&#39;: 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頁面也是可以用的,哈哈。


相關推薦:

php 縮放圖片實例簡介

JavaScript等比例縮放圖片

php等比例縮放圖片及剪下圖片程式碼分享#

以上是微信小程式實現手指縮放圖片程式碼分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn