title: camera 相机 header: develop nav: component

sidebar: media_camera

解释:系统相机,使用该组件需通过获取用户权限设置申请授权后方可对用户发起授权申请,可在需授权接口列表中查看相关错误码信息。

属性说明

属性名 类型 默认值 必填 说明
device-position String back 前置或后置,值为front, back
flash String auto 闪光灯,值为auto, on, off
bindstop EventHandle 摄像头在非正常终止时触发,如退出后台等情况
binderror EventHandle 用户不允许使用摄像头时触发

device-position 有效值

说明
front 前置摄像头
back 后置摄像头

flash 有效值

说明
auto 自动闪光灯
on 闪光灯开
off 闪光灯关

示例

在开发者工具中预览效果

扫码体验

sidebar: media_camera - 图1 请使用百度APP扫码

代码示例

在开发者工具中预览效果

:::codeTab

  1. <div class="camera">
  2. <camera device-position="{{device}}"
  3. flash="off"
  4. bindstop="stop"
  5. binderror="error"
  6. style="width: 100%; height: 3rem;">
  7. </camera>
  8. <button type="primary" bind:tap="switchCamera">切换摄像头</button>
  9. <button type="primary" bind:tap="takePhoto">拍照</button>
  10. <button type="primary" bind:tap="startRecord">开始录像</button>
  11. <button type="primary" bind:tap="stopRecord">结束录像</button>
  12. <view class="preview">预览</view>
  13. <image s-if="src" class="img" mode="widthFix" src="{{src}}"></image>
  14. <video s-if="videoSrc" class="video" src="{{videoSrc}}"></video>
  15. </div>
  1. Page({
  2. data: {
  3. src: '',
  4. device: 'back',
  5. videoSrc: ''
  6. },
  7. onShow() {
  8. console.log("目前此组件的录像功能在安卓端不能播放,请在开发者工具中查看完整效果");
  9. },
  10. switchCamera() {
  11. const devices = this.getData('device');
  12. if (devices === 'back') {
  13. this.setData({
  14. device: 'front'
  15. });
  16. } else {
  17. this.setData({
  18. device: 'back'
  19. });
  20. }
  21. },
  22. takePhoto() {
  23. const ctx = swan.createCameraContext();
  24. ctx.takePhoto({
  25. quality: 'high',
  26. success: res => {
  27. this.setData({
  28. src: res.tempImagePath
  29. });
  30. }
  31. });
  32. },
  33. startRecord() {
  34. const ctx = swan.createCameraContext();
  35. ctx.startRecord({
  36. success: res => {
  37. swan.showToast({
  38. title: 'startRecord'
  39. });
  40. }
  41. });
  42. },
  43. stopRecord() {
  44. const ctx = swan.createCameraContext();
  45. ctx.stopRecord({
  46. success: res => {
  47. swan.showModal({
  48. title: '提示',
  49. content: res.tempVideoPath
  50. });
  51. this.setData({
  52. videoSrc: res.tempVideoPath
  53. });
  54. }
  55. });
  56. },
  57. error(e) {
  58. console.log(e.detail);
  59. }
  60. });

:::

Bug & Tip

  • Tip:camera 组件是由客户端创建的原生组件,它的层级是最高的,不能通过 z-index 控制层级。可使用 cover-view cover-image 覆盖在上面(在基础库3.0.0之前需要先创建camera,再通过的方式方 s-if="{ {true} }"可在camera上创建NA组件)。
  • Tip:同一页面只能插入一个 camera 组件。
  • Tip:请勿在 scroll-view、swiper、picker-view、movable-view 中使用 camera 组件。
  • Tip:相关API:createCameraContext