微信小程序怎样实现手指缩放图片

  介绍

这篇文章将为大家详细讲解有关微信小程序怎样实现手指缩放图片,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

用手指缩放图片。其实在实现这个需求以前,并不知道,微信公众号以及微信小程序里面有一个原生的api就自带这个特效,而且微信朋友圈也是用的这个api.wx。previewImage,就是它。预览图片。除了不能预览开发环境的本地电脑的图片外,你手机真机的图片,以及http服务器上的图片都是可以预览的,而且缩放功能做得很流畅。本文主要和大家介绍了微信小程序中实现手指缩放图片的示例代码。

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

页面({   ,,数据:{   ,,,触摸:,{   ,,,,,距离:,0,   ,,,,,:,1,   ,,,,,baseWidth:,空,   ,,,,,baseHeight:,空,   ,,,,,scaleWidth:,空,   ,,,,,scaleHeight:零   ,,,}   ,,},   ,,touchstartCallback:函数(e), {   ,,,//,单手指缩放开始,也不做任何处理   ,,,如果(==e.touches.length  1),返回   ,,,console.log(& # 39;双手指触发开始& # 39;)   ,,,//,注意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 ({   ,,,,,& # 39;touch.distance& # 39;:,距离,   ,,,})   ,,},   ,,touchmoveCallback:函数(e), {   ,,,let  touch =this.data.touch   ,,,//,单手指缩放我们不做任何操作   ,,,如果(==e.touches.length  1),返回   ,,,console.log(& # 39;双手指运动& # 39;)   ,,,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);   ,,,let  distanceDiff =, distance 作用;touch.distance;   ,,,let  newScale =, touch.scale  +, 0.005, * distanceDiff   ,,,//,为了防止缩放得太大,所以规模需要限制,同理最小值也是   ,,,如果(newScale 祝辞=,2),{   ,,,,,newScale =2   ,,,}   ,,,如果(newScale  & lt;=, 0.6), {   ,,,,,newScale  0.6=,   ,,,}   ,,,let  scaleWidth =, newScale  * touch.baseWidth   ,,,let  scaleHeight =, newScale  * touch.baseHeight   ,,,//,赋值,新的,=祝辞,旧的   ,,,this.setData ({   ,,,,,& # 39;touch.distance& # 39;:,距离,   ,,,,,& # 39;touch.scale& # 39;:, newScale,   ,,,,,& # 39;touch.scaleWidth& # 39;:, scaleWidth,   ,,,,,& # 39;touch.scaleHeight& # 39;:, scaleHeight,   ,,,,,& # 39;touch.diff& # 39;: distanceDiff   ,,,})   ,,},   ,,bindload:函数(e), {   ,,//,bindload 这个api是& lt; image>组件的api类似& lt; 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文件对应如下,就不做解释了:

& lt; view 类=癱ontainer"比;   & lt;才能view  bindtouchmove=皌ouchmoveCallback", bindtouchstart=皌ouchstartCallback"比;   ,,,& lt; image  src=https://www.yisu.com/zixun/resources/pic/cat.jpg”风格="宽度:{{联系。scaleWidth}} px;高度:{{联系。scaleHeight}} px bindload“bindload=>      

写到这里发现,就算小程序用不了这个js,我的ht5页面也是可以用的,哈哈。

关于“微信小程序怎样实现手指缩放图片”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看的到。

微信小程序怎样实现手指缩放图片