您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

微信小程序中实现手指缩放图片的示例代码

2024/2/20 4:25:55发布30次查看
本篇文章主要介绍了微信小程序中实现手指缩放图片的示例代码,现在分享给大家,也给大家做个参考。
公司开发微信小程序,pm想实现如下需求:
用手指缩放图片。其实在实现这个需求以前,并不知道,微信公众号以及微信小程序里面有一个原生的api就自带这个特效,而且微信朋友圈也是用的这个api。wx.previewimage,就是它。预览图片。除了不能预览开发环境的本地电脑的图片外,你手机真机的图片,以及http服务器上的图片都是可以预览的,而且缩放功能做得很流畅。下面就说说如何用js来实现这个功能吧。
先上源码,然后在逐步剖析:
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({ 'touch.distance': distance, 'touch.scale': newscale, 'touch.scalewidth': scalewidth, 'touch.scaleheight': scaleheight, 'touch.diff': distancediff }) }, bindload: 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文件对应如下,就不做解释了:
<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>
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
vue项目中如何引入icon图标
javascript中的e-mail 地址格式验证
javascript性能优化之分时函数的介绍
以上就是微信小程序中实现手指缩放图片的示例代码的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product