微信小程序实现通过双向滑动缩放图片大小的示例分析

发布时间:2021-06-29 15:30:58 作者:小新
来源:亿速云 阅读:246

这篇文章主要介绍了微信小程序实现通过双向滑动缩放图片大小的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

本文实例讲述了微信小程序实现通过双向滑动缩放图片大小的方法。分享给大家供大家参考,具体如下:

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

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. 微信小程序如何实现左右滑动

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

微信小程序

上一篇:vim vax 快捷键有哪些

下一篇:如何解决phpMyAdmin中缺少mysqli扩展问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》