微信小程序-倒计时调用相机自动拍照

在某些进行签到的场景,为了防止用户选择相册的照片或者不实时拍照,设置相机倒计时自动拍照。

一、首先是视图层index.wxml,视图层主要负责显示组件和图片。

<!--index.wxml-->

< view class= "userinfo-login" >
< view class= "page-body" >
< view class= "page-body-wrapper" >
< view wx:if= "{{src}}" ></ view >
<!-- 如果存在已经拍好的照片就不再显示调用摄像头的组件-->
< view wx:else >
< camera device-position= "back" flash= "off" binderror= "error" style= "width: 100%; height: 200px;" ></ camera >
  <!-- 调用摄像头的组件-->
</ view >
< image wx:if= "{{src}}" mode= "widthFix" src= "{{src}}" ></ image >
        <!-- 显示拍好的照片-->
</ view >
</ view >
</ view >

二、逻辑层index.js,调用倒计时函数并且调用摄像头拍照并保存图片。

//index.js

const app = getApp ()
Page ({
data : {
userInfo : {},
counting : false //倒计时
},
onLoad : function () {
this .daojishi (); //一进来就拍照倒计时
this .ctx = wx .createCameraContext ()//创建摄像头对象
},
//倒计时
daojishi : function () {
var that = this ;
if (!that .data .counting ) {
//开始倒计时5秒
countDown (that , 5 );
}
}
})

//倒计时函数 在page外

function countDown (that , count ) {
if (count == 0 ) {
//等于0时拍照
that .ctx .takePhoto ({
quality : 'high' ,
success : (res ) => {
that .setData ({
src : res .tempImagePath
})
wx .showToast ({
title : '拍照完成' ,
})
}
})
that .setData ({
counting : false
})
return ;
}
wx .showLoading ({//加载时显示倒计时
title : '拍照倒计时' +count + '秒' ,
})

setTimeout ( function () {
wx .hideLoading ()
}, 1000 )
that .setData ({
counting : true ,
})
setTimeout ( function () {
count --;
countDown (that , count );
}, 1000 );
}


主要实现就是这样。

猜你喜欢

转载自blog.csdn.net/weixin_36708477/article/details/80242663