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

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' });
  }
});
相关推荐
px不是xp2 小时前
微信小程序组件化开发最佳实践
微信小程序·小程序·notepad++
code_Bo2 小时前
kiro生成小程序商业案例
前端·微信小程序·小程序·云开发
克里斯蒂亚诺更新4 小时前
微信小程序引入vant weapp,button宽度100%
微信小程序·小程序
nhc08815 小时前
贵阳纳海川·花卉游戏行业解决方案
人工智能·游戏·微信小程序·软件开发·小程序开发
普通人619 小时前
微信小程序又双叒叕改获取头像昵称的接口了
微信小程序·小程序·notepad++
大黄说说2 天前
SaaS小程序制作平台对比:码云数智、有赞、微盟
微信小程序
清风絮柳3 天前
65.少儿英语微信小程序
vue.js·spring boot·微信小程序·小程序·毕业设计
tjsoft3 天前
unigui开发微信小程序
微信小程序·小程序
苏灵凯5 天前
智能环境监测终端全栈设计:从单片机到微信小程序,手把手搞定!
单片机·嵌入式硬件·mcu·物联网·微信小程序·小程序·蓝牙模块