实现原理
通过小程序组件 <camera> 中的 flash 属性的控制实现后置闪光灯的打开与关闭
页面部分
注意:mode="scanCode" 只有扫码模式才能准确控制闪光灯的开关
/* flashlight.wxml */ <view class="lightBox"> <view class="topBtn"> <view bindtap="changeType" data-type="flash" class="flash btnItem {{ activeType == 'flash' ? 'active' : '' }}">闪光</view> <view bindtap="changeType" data-type="sos" class="sos btnItem {{ activeType == 'sos' ? 'activeRed' : '' }}">SOS</view> </view> <view bindtap="changeType" data-type="light" class="lightClose {{ activeType == 'light' ? 'active' : '' }}"> <text class="iconfont icon-close"></text> </view> <!-- 注:mode="scanCode" 只有扫码模式才能准确控制闪光灯的开关 --> <camera wx:if="{{ showCamera }}" resolution="low" mode="scanCode" flash="{{ flash }}" class="camera"></camera> </view>
逻辑处理部分
1.因防止打开子页面加载摄像头会延迟卡顿,所以暂时通过 **showCamera** 进入页面不立即进行加载,提升流畅度。
/* 延迟加载摄像头, 防止进入页面时卡顿 */ onLoad: function (options) { pageUtil.setNavBar(options) setTimeout(() => { this.setData({ showCamera: true }) }, 1000); },
2.切换开关控制
toggleLight(value) { // 切换开关 this.setData({ flash: value ? value : (this.data.flash === 'off' ? 'on' : 'off') }) },