微信小程序 摄像头 授权同页面丝滑调用

page.wxml .wxss .json

typescript 复制代码
<view wx:if="{{showCamera}}" style="width:100%;height:500rpx;">
  <camera class="camera" device-position="back" flash="off" binderror="onCameraError"></camera>
</view>

<button wx:if="{{showCamera}}" bindtap="takePhoto" type="primary">拍照</button>
<image wx:if="{{photoPath}}" src="{{photoPath}}" mode="widthFix" />
typescript 复制代码
.camera {
  width: 100%;
  height: 100%;
  display: block;
}
typescript 复制代码
{
  "permission": {
    "scope.camera": {
      "desc": "用于拍摄照片"
    }
  }
}

page.js

typescript 复制代码
Page({
  data: {
    cameraAuth: false,
    showCamera: false,
    cameraContext: null,
    photoPath: ''
  },

  onLoad() {
    this.checkCameraAuth();
  },

  onShow() {
    if (!this.data.cameraAuth) {
      this.checkCameraAuth(true);
    }
  },

  // 检查权限
  checkCameraAuth(isShow = false) {
    wx.getSetting({
      success: (res) => {
        const hasAuth = res.authSetting['scope.camera'];
        this.setData({ cameraAuth: hasAuth });

        if (hasAuth) {
          this.openCamera();
          return;
        }

        if (isShow) return;

        wx.showModal({
          title: '需要摄像头权限',
          content: '请允许使用摄像头',
          confirmText: '去授权',
          success: (r) => {
            if (r.confirm) this.openAuthDialog();
          }
        })
      }
    })
  },

  // 打开授权
  openAuthDialog() {
    wx.authorize({
      scope: 'scope.camera',
      fail: () => {
        wx.showModal({
          title: '未授权',
          content: '请去设置开启权限',
          confirmText: '去设置',
          success: (r) => {
            if (r.confirm) wx.openSetting();
          }
        })
      },
      success: () => {
        // 系统授权的时候 success监听回调 关键!!  当前页面无需二次刷新
        this.checkCameraAuth(true);
      },
    })
  },

  // ✅ 启动相机(修复不显示问题)
  openCamera() {
    setTimeout(() => {
      this.setData({ showCamera: true });
      const cameraContext = wx.createCameraContext();
      this.setData({ cameraContext });
    }, 300);
  },

  // 拍照
  takePhoto() {
    this.data.cameraContext.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({ photoPath: res.tempImagePath });
        wx.previewImage({ urls: [res.tempImagePath] });
      }
    })
  },

  // 相机错误
  onCameraError(e) {
    console.error('相机异常', e);
    wx.showToast({ title: '相机启动失败', icon: 'none' });
  }
});
相关推荐
这是个栗子10 小时前
【uni-app微信小程序问题解决】Uni-app 微信小程序组件不渲染
微信小程序·小程序·uni-app
倒流时光三十年10 小时前
第四章 WXSS 样式系统与布局
spring boot·微信小程序
爱学习 爱分享1 天前
微信小程序html 在 webview 会打开再缩放一下
微信小程序·小程序·html
xshirleyl1 天前
微信小程序开发week6-慕尚花坊项目
微信小程序·小程序
好赞科技1 天前
2026年八大上门服务预约小程序:解锁高效生活新体验
大数据·微信小程序
编程猪猪侠1 天前
uni-app微信小程序车牌号输入组件实现
微信小程序·uni-app
客场消音器2 天前
如何使用codex进行UI重构,让AI开发的前端页面不再千篇一律
前端·后端·微信小程序
打瞌睡的朱尤2 天前
微信小程序126~160
微信小程序·小程序
腾讯云云开发2 天前
小程序成长计划正式接入Hy3 preview
微信小程序
bruce541102 天前
讲讲 RTMate (WebSocket as A Service)中的消息的发布订阅机制
后端·微信小程序