欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

微信小程序实现通过双向滑动缩放图片大小的方法

时间:2021-02-20 09:07:49|栏目:JavaScript代码|点击:

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

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

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>

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

希望本文所述对大家微信小程序开发有所帮助。

上一篇:原生js实现半透明遮罩层效果具体代码

栏    目:JavaScript代码

下一篇:浅谈javascript中执行环境(作用域)与作用域链

本文标题:微信小程序实现通过双向滑动缩放图片大小的方法

本文地址:http://www.codeinn.net/misctech/66574.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有