话不多说,直接上代码,代码里面注释写的都很详细
wxml文件:
<!-- 相机 -->
<camera wx:if="{{!videoSrc}}" device-position="back" flash="off" binderror="error" class="photo">
<cover-view>
<!-- 拍照按钮 -->
<button class="photo_btn" bindtouchstart="handleTouchStart" bindtouchend="handleTouchEnd" bindlongpress="handleLongPress" bindtap="handleClick">
点击/长按</button>
</cover-view>
</camera>
<!-- 拍完显示照片/视频 -->
<image wx:if="{{imageSrc}}" src='{{imageSrc}}'></image>
<video wx:if="{{videoSrc}}" src="{{videoSrc}}" controls></video>
wxss文件:
可根据项目实际情况自己调整
.photo{
width: 100%;
height: 100%;
position: fixed;
top: 0;
}
.photo_btn{
width: 100rpx;
height: 100rpx;
border-radius: 50%;
position: absolute;
left: calc(50% - 50rpx);
bottom: 50rpx;
}
js文件:
Page({
/**
* 页面的初始数据
*/
data: {
imageSrc: '',//图片url
videoSrc: '',//视频url
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
this.ctx = wx.createCameraContext();
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
},
/**
*拍照的方法
*/
takePhoto() {
this.ctx.takePhoto({
quality: 'high',
success: (res) => {
this.setData({
imageSrc: res.tempImagePath
})
},
fail() {
//拍照失败
console.log("拍照失败");
}
})
},
/**
* 开始录像的方法
*/
startShootVideo() {
console.log("========= 调用开始录像 ===========")
this.ctx.startRecord({
success: (res) => {
wx.showLoading({
title: '正在录像',
})
},
fail() {
console.log("========= 调用开始录像失败 ===========")
}
})
},
/**
* 结束录像
*/
stopShootVideo() {
console.log("========= 调用结束录像 ===========")
this.ctx.stopRecord({
success: (res) => {
wx.hideLoading();
this.setData({
videoSrc: res.tempVideoPath,
})
},
fail() {
wx.hideLoading();
console.log("========= 调用结束录像失败 ===========")
}
})
},
//touch start 手指触摸开始
handleTouchStart: function(e) {
this.startTime = e.timeStamp;
console.log(" startTime = " + e.timeStamp);
console.log(" 手指触摸开始 " , e);
console.log(" this " , this);
},
//touch end 手指触摸结束
handleTouchEnd: function(e) {
this.endTime = e.timeStamp;
console.log(" endTime = " + e.timeStamp);
console.log(" 手指触摸结束 ", e);
//判断是点击还是长按 点击不做任何事件,长按 触发结束录像
if (this.endTime - this.startTime > 350) {
//长按操作 调用结束录像方法
this.stopShootVideo();
}
},
/**
* 点击按钮 - 拍照
*/
handleClick: function(e) {
console.log("endTime - startTime = " + (this.endTime - this.startTime));
if (this.endTime - this.startTime < 350) {
console.log("点击");
//调用拍照方法
this.takePhoto();
}
},
/**
* 长按按钮 - 录像
*/
handleLongPress: function(e) {
console.log("endTime - startTime = " + (this.endTime - this.startTime));
console.log("长按");
// 长按方法触发,调用开始录像方法
this.startShootVideo();
},
})