// pages/home/camera/index.js import * as model from '../../../services/tf/model' Page({ /** * 页面的初始数据 */ data: { isAuth: false, src: '', fps: 0, predicting: false, cameraContext: null, cameraListener: null, lastTime: 0 }, /** * 生命周期函数--监听页面加载 */ onLoad(options) { this.setData({ lastTime: Date.now() }) this.initModel(); }, initModel: async function () { this.showLoadingToast(); await model.load(); this.hideLoadingToast(); if (!model.isReady()) { wx.showToast({ title: '网络连接异常', icon: 'none' }); } }, showLoadingToast: function () { wx.showLoading({ title: '拼命加载模型', }); }, hideLoadingToast: function () { wx.hideLoading() }, openCamera() { this.setData({ cameraContext: wx.createCameraContext() }) this.setData({ cameraListener: this.data.cameraContext.onCameraFrame(frame => { this.executePredict(frame) }) }) this.data.cameraListener.start(); }, executePredict(frame) { if (!this.data.predicting && model.isReady()) { this.setData({ predicting: true }, async () => { const now = Date.now() // model.predict(frame) // const predictionResults = await model.classify(frame) // console.log(now - this.data.lastTime); model.predict(frame) this.setData({ predicting: false, fps: (1000 / (now - this.data.lastTime)).toFixed(2), lastTime: now }) }) } }, openSetting() { const _this = this let promise = new Promise((resolve, reject) => { wx.showModal({ title: '授权', content: '请先授权获取摄像头权限', success(res) { if (res.confirm) { wx.openSetting({ success(res) { if (res.authSetting['scope.camera']) { // 用户打开了授权开关 resolve(true) } else { // 用户没有打开授权开关, 继续打开设置页面 _this.openSetting().then(res => { resolve(true) }) } }, fail(res) { console.log(res) } }) } else if (res.cancel) { _this.openSetting().then(res => { resolve(true) }) } } }) }) return promise; }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady() { const _this = this wx.getSetting({ success: res => { if (res.authSetting['scope.camera']) { // 用户已经授权 _this.setData({ isAuth: true }) _this.openCamera() } else { // 用户还没有授权,向用户发起授权请求 wx.authorize({ scope: 'scope.camera', success() { // 用户同意授权 _this.setData({ isAuth: true }) _this.openCamera() }, fail() { // 用户不同意授权 _this.openSetting().then(res => { _this.setData({ isAuth: false }) }) } }) } }, fail: res => { console.log('获取用户授权信息失败') } }) }, /** * 生命周期函数--监听页面显示 */ onShow() { }, /** * 生命周期函数--监听页面隐藏 */ onHide() { }, /** * 生命周期函数--监听页面卸载 */ onUnload() { this.data.cameraListener.stop(); }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh() { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom() { }, /** * 用户点击右上角分享 */ onShareAppMessage() { } })