實現原理
通過小程序組件 <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')
})
},
效果體驗,歡迎掃碼使用或微信小程序搜索 - "辛巴達盒子"

