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

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' });
  }
});
相关推荐
爱分享的小诺1 天前
微信小程序2.0人脸审核,1.0升级到2.0
微信小程序·小程序
打瞌睡的朱尤1 天前
微信小程序(黑马)4-5
微信小程序·小程序
凌奕2 天前
微信小程序接入微信 AI:让用户"说一句话"就能下单
微信·微信小程序·agent
倒流时光三十年2 天前
第十八章 搜索历史保存功能实现记录
spring boot·微信小程序
倒流时光三十年2 天前
第十七章 投票页面增加搜索功能
spring boot·微信小程序
静Yu2 天前
我用Codex开发的第一个朋友圈九宫格素材小程序上线啦
微信小程序·小程序·云开发
kyriewen3 天前
一个人+Cursor,7天上线付费小程序:第1天我就想放弃了
前端·微信小程序·cursor
暗不需求3 天前
从路虎汽车小程序看微信小程序开发的最佳实践
前端·javascript·微信小程序
aiguangyuan4 天前
微信小程序服务商
微信小程序·前端开发
一支帆4 天前
微信小程序-情侣点餐
java·微信小程序·情侣点餐