zl程序教程

您现在的位置是:首页 >  工具

当前栏目

微信小程序调用摄像头实现拍照功能

微信程序 实现 功能 调用 摄像头 拍照
2023-06-13 09:11:02 时间

WXML文件代码

    重新拍照
    
    提交图片

JS文件代码

Page({
  data: {
    cameraStatus: false,
    src: '',
  },
  onLoad() {
    const _this = this
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.camera']) {
          _this.setData({
            cameraStatus: true
          })
        } else {
          // 用户还没有授权,向用户发起授权请求
          wx.authorize({
            scope: 'scope.camera',
            success() { // 用户同意授权
              _this.setData({
                cameraStatus: true
              })
            },
            fail() { // 用户不同意授权
              _this.openSetting().then(res => {
                _this.setData({
                  cameraStatus: true
                })
              })
            }
          })
        }
      },
      fail: res => {
        console.log('获取用户授权信息失败')
      }
    })
  },

  // 打开授权设置界面
  openSetting() {
    const _this = this
    let promise = new Promise((resolve, reject) => {
      wx.showModal({
        title: '授权',
        content: '请先授权获取摄像头权限',
        success(res) {
          if (res.confirm) {
            wx.openSetting({
              success(res) {
                if (res.authSetting['scope.camera']) { // 用户打开了授权开关
                  resolve(true)
                } else {
                  // 用户没有打开授权开关, 继续打开设置页面
                  _this.openSetting().then(res => {
                    resolve(true)
                  })
                }
              },
              fail(res) {
                console.log(res)
              }
            })
          } else if (res.cancel) {
            _this.openSetting().then(res => {
              resolve(true)
            })
          }
        }
      })
    })
    return promise;
  },
  // 拍照
  takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath,
          cameraStatus: false
        })
      }
    })
  },
  // 重新拍照
  rePhoto() {
    this.setData({
      cameraStatus: true,
      src: ''
    })
  }
})

WXSS文件代码

.content {
  padding: 0;
  margin: 0;
  position: fixed;
  width: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  justify-content: space-between;
  overflow: hidden;
  height: 100vh;
}

image {
  margin: 0;
  padding: 0;
}

.content .camera-con {
  flex: 1;
  overflow: hidden;
}

.content .camera-con image,
.content .camera-con camera {
  width: 100%;
  height: calc(100vh - 148rpx);
}

.content .btn-con {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 148rpx;
  background-color: #333333;
}

.content .btn-con button {
  margin: 0 30rpx;
}

.content .btn-con .take {
  border: 2rpx solid #FFFFFF;
  border-radius: 50%;
  height: 93rpx;
  width: 93rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}