話不多說,直接上代碼,代碼裏面註釋寫的都很詳細
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();
},
})