小程序使用相机

1、相机组件

  • 页面引入相机 (camera.wxml)
<!-- 相机 -->
<camera wx:if="{{showCamera}}" device-position="{{cameraConfig.position}}" flash="{{cameraConfig.flash}}" bindstop="cameraStop" binderror="cameraError" class="cameraBox">
  <cover-view class="viewBox">
    <cover-view style='background-color: #fff;flex:1;'></cover-view>
    <cover-view class="content">
      <cover-image mode='widthFix' class="faceImg" src="/icon/face.png" />
      <cover-view class="circle"></cover-view>
    </cover-view>
    <cover-view style='background-color: #fff;flex:1;'></cover-view>
  </cover-view>

  <cover-view class="cameraTab">
    <cover-image class="tabImg" src="/icon/{{cameraConfig.flash}}.png" bindtap='flashChange'></cover-image>
    <cover-image class="tabImg" src="/icon/switch.png" bindtap='positionChange'></cover-image>
    <cover-view bindtap='cameraDisable'>取消</cover-view>
  </cover-view>
  <cover-view class="photographBtn" bindtap='takePhoto'>
    <cover-image class="cameraImg" src="/icon/camera.png"></cover-image>
  </cover-view>
</camera>
const userAPI = require('../../model/user')
const mimeMap = require('../../utils/mime')

Component({
  properties: {
    img_type: {
      type: String,
      value: 'images/'
    }
  },

  data: {
    showCamera: false, // 显示相机
    cameraConfig: {
      position: 'front',
      flash: 'off'
    },
  },

  created() {
    // 初始化
    this.showCamera = false //是否显示照相机
    this.cameraConfig = { //照相机参数配置
      flash: 'off',
      position: 'front'
    }
  },

  methods: {
    uploadFile(filePath, data) { // 移动云获取签名, 非必要, 与后端沟通需求
      const host = 'https://...';
      wx.uploadFile({
        url: host,
        filePath: filePath,
        name: 'file',
        formData: {
          'key': data.key,
          'acl': data.acl,
          'Content-Type': data.contentType,
          'X-Amz-Credential': data.x_amz_credential,
          'X-Amz-Algorithm': data.x_amz_algorithm,
          'X-Amz-Date': data.x_amz_date,
          'Policy': data.policy,
          'X-Amz-Signature': data.x_amz_signature
        },
        success: (res) => {
          // console.log('uploadFile', res);
          if (res.statusCode === 204) {
            wx.showToast({
              title: '上传成功!',
              icon: 'none',
            });
            userAPI.fileUrl(data.key).then(result => {
              // 向父组件传递数据
              this.triggerEvent('takePhoto', {
                href: result,
                upHref: data.key,
              })
            })
          }
        },
        fail: err => {
          console.log(err);
        }
      });
    },
    // 调用相机
    cameraDisable() {
      let self = this;
      self.showCamera = !self.showCamera;
      self.setData({
        showCamera: self.showCamera
      })
    },
    // 拍照
    takePhoto(e) {
      var self = this;
      wx.showLoading({
        title: '上传中...',
      })
      const ctx = wx.createCameraContext()
      ctx.takePhoto({
        quality: 'normal',
        success: res => {
          console.log(res)
          let extension = res.tempImagePath.split('.')[1];
          self.cameraDisable();
          let signParams = {
            key: 'face/' + res.tempImagePath.split('\/\/')[1], // 处理文件路径, 与后端沟通
            acl: 'private',
            content_type: mimeMap.getMimeType(extension)
          }
          // 图片加密, 非必要, 与后端沟通要求
          userAPI.sign(signParams).then(result => {
            // console.log(result);
            self.uploadFile(res.tempImagePath, result)
          }).catch(err => {
            console.log(err);
          })
        }
      })
    },
    // 照相机停止运行
    cameraStop: function (e) {
      this.cameraDisable();
      app.showNone('相机停止运行')
    },
    // 照相机没授权
    cameraError: function (e) {
      var self = this;
      self.setData({
        showCamera: false
      })
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.camera'] == false) {
            wx.showModal({
              title: '摄像头授权',
              content: '您未开启相机权限,无法上传照片,是否开启',
              cancelText: '取消',
              confirmText: '开启',
              success: (res) => {
                if (res.confirm) {
                  wx.openSetting({
                    success: res => {
                      this.cameraDisable(); // 开启相机
                    }
                  })
                } else if (res.cancel) {
                  wx.showToast({
                    icon: "none",
                    title: '您未开启相机权限,无法上传照片,需要开启相机权限',
                    duration: 4000,
                  })
                }
              }
            })
          }
        }
      })
    },
    // 切换闪光灯状态
    flashChange: function () {
      switch (this.cameraConfig.flash) {
        case 'off':
          this.cameraConfig.flash = 'on';
          break;
        case 'on':
          this.cameraConfig.flash = 'auto';
          break;
        case 'auto':
          this.cameraConfig.flash = 'off';
          break;
      }
      this.setData({
        cameraConfig: this.cameraConfig
      })
      console.log('切换闪光灯状态');
    },
    // 切换前后置摄像头
    positionChange() {
      switch (this.cameraConfig.position) {
        case 'front':
          this.cameraConfig.position = 'back';
          break;
        case 'back':
          this.cameraConfig.position = 'front';
          break;
      }

      this.setData({
        cameraConfig: this.cameraConfig
      })

      console.log('切换前后置摄像头');
    }
  }
})

  • 页面样式 
/* 照相机 */
.cameraBox {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 10000;
}

.viewBox {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 1000;
  display: flex;
  align-items: stretch;
  flex-direction: column;
}

/* 顶部设置导航 */
.cameraTab {
  position: fixed;
  left: 0;
  top: 0;
  width: 94vw;
  height: 12vw;
  padding: 0 3vw;
  background-color: rgba(0, 0, 0, .8);
  z-index: 1000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 32rpx;
  color: #fff;
}

.cameraTab .tabImg {
  width: 7vw;
  height: 7vw;
}

.content {
  width: 100vw;
  height: 100vw;
  position: relative;
}

/* 相机遮罩图片 */
.faceImg {
  width: 100vw;
  height: 100vw;
  padding: 0;
  margin: 0;
}

/* 圆圈 */
.circle {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 80vw;
  height: 80vw;
  border-radius: 50%;
  border: 10rpx solid #ccc;
}

/* 拍照按钮 */
.photographBtn {
  position: fixed;
  bottom: 10vw;
  left: 0;
  right: 0;
  margin: auto;
  z-index: 10000;
  width: 120rpx;
  height: 120rpx;
  padding: 0;
  border-radius: 50%;
  background-color: red;
  border: 10rpx solid #eee;

  display: flex;
  align-items: center;
  justify-content: center;
}

.photographBtn .cameraImg {
  width: 70rpx;
  height: 70rpx;
}
  •  组件配置
{
  "component": true, // 设置为true
}

2、使用相机

<!-- 相机 -->
<component-camera id="camera" wx:if="{{showCamera}}" bindtakePhoto="takePhoto"></component-camera>
  // 调用相机
  useCamera() {
    this.setData({
      showCamera: true
    })
    this.selectComponent("#camera").cameraDisable();
  },
  takePhoto(e) {
    var href = "userInfo.href";
    this.setData({
      [href]: e.detail.href,
      upHref: e.detail.upHref
    })
  },
{
  "usingComponents": {
    "component-camera": "/components/camera/camera", // 注册组件
  }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值