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

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' });
  }
});
相关推荐
蜗牛前端2 天前
codex 全流程开发上线的高颜值礼簿小程序
前端·微信小程序
爱勇宝6 天前
我想认真做一件小事:让孩子和家长更好地互动
微信小程序·小程序·云开发
唯火锅不可辜负6 天前
避坑指南:iOS 下 scroll-view 嵌套 fixed 布局的“翻车”现场与修复
微信小程序
didiplus6 天前
运维人的随身神器:我把25个常用工具塞进了微信小程序
微信小程序
一份执念7 天前
uni-app 小程序分包限制处理与主包体积优化实战
前端·微信小程序
一份执念7 天前
ECharts 安装与使用完全指南:从全量引入到小程序分包优化
微信小程序·echarts
skiyee8 天前
🔥UniApp 仅需 5 行代码!实现所有页面中控制应用主题变化
前端·微信小程序
Jinkey9 天前
要用户手机号真的是为了打骚扰电话吗?浅谈微信生态会员账号体系与资产合并
后端·微信·微信小程序
用户43242810611411 天前
微信小程序从0到1接入微信支付的完整攻略
微信小程序
spmcor13 天前
微信小程序 setStorageSync 踩坑实录:别让"顺手一存"变成"隐形炸弹"
微信小程序