推荐答案
<view> <camera mode="normal" device-position="back" flash="off" binderror="error" style="width: 100%; height: 300px;"></camera> <button bindtap="takePhoto">拍摄照片</button> <button bindtap="startRecord">开始录制</button> <button bindtap="stopRecord">停止录制</button> </view>
// www.javascriptcn.com code example
Page({
takePhoto() {
const ctx = wx.createCameraContext()
ctx.takePhoto({
quality: 'high',
success: (res) => {
this.setData({
src: res.tempImagePath
})
}
})
},
startRecord() {
const ctx = wx.createCameraContext()
ctx.startRecord({
success: (res) => {
console.log('开始录制')
}
})
},
stopRecord() {
const ctx = wx.createCameraContext()
ctx.stopRecord({
success: (res) => {
this.setData({
src: res.tempThumbPath,
videoSrc: res.tempVideoPath
})
}
})
}
})本题详细解读
1. camera 组件的基本使用
camera 组件是微信小程序中用于拍摄照片或录制视频的核心组件。通过设置 mode 属性,可以控制相机的工作模式。device-position 属性用于指定使用前置或后置摄像头,flash 属性用于控制闪光灯的开关。
2. 拍摄照片
使用 wx.createCameraContext() 创建一个相机上下文对象,然后调用 takePhoto 方法拍摄照片。takePhoto 方法可以设置照片的质量(quality),拍摄成功后,照片的临时路径会通过 res.tempImagePath 返回。
3. 录制视频
录制视频的过程分为开始录制和停止录制两个步骤。通过 startRecord 方法开始录制,录制成功后可以通过 stopRecord 方法停止录制。停止录制后,视频的临时路径会通过 res.tempVideoPath 返回,同时还会返回视频的封面图路径 res.tempThumbPath。
4. 错误处理
在 camera 组件中,可以通过 binderror 属性绑定一个错误处理函数,当相机发生错误时,会触发该函数。开发者可以在该函数中处理相机错误,例如提示用户检查相机权限等。
5. 样式与布局
camera 组件的样式可以通过 style 属性进行设置,通常需要设置宽度和高度以适应页面布局。拍摄照片和录制视频的按钮可以通过 button 组件实现,并通过 bindtap 绑定相应的事件处理函数。