微信小程序实现图片双滑缩放大小



在做小程序开发的过程中,后端传来一张图片地图,需要实现双手指滑动,使图片缩放,最终得出了一下代码:

  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>


最后,通过手机预览,就会发现已达到预想的效果!


作者: ~逍遥★星辰~
链接: 微信小程序实现图片双滑缩放大小-教程-小程序社区-微信小程序-微信小程序开发社区-小程序开发论坛-微信小程序联盟
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值