Sow nothing reap nothing

微信小程序自定义相机取景框简单实现

已有3,913次关注

实现思路:使用媒体组件camera使用设备相机功能,再使用覆盖原生组件的cover-viewcover-image实现相机之上的取景框,当然取景框为背景透明图片。目前微信小程序原生组件已经支持同层渲染,文中cover-viewcover-image也可以使用viewimage来替代实现。其中camera使用还涉及到scope.camera授权,可自行添加授权代码。
微信小程序自定义相机取景框简单实现.png

wxml代码:

<view class="camera_box">
  <camera class="camera" wx:if="{{!btnShow}}" device-position="back" flash="off">
    <cover-view class="cover_view">
      <cover-image class="cover_legend" src="test/frame.png"></cover-image>
    </cover-view>
  </camera>
  <image class="camera_thumb" src="{{idCardUrl}}" wx:if="{{btnShow}}"></image>
  <view class="camera_btn">
    <image src="test/taking_pictures.png" mode="widthFix" bindtap="takeingPhoto" wx:if="{{!btnShow}}"></image>
    <image src="test/taking_confirm.png" mode="widthFix" bindtap="savePhoto" wx:if="{{btnShow}}"></image>
    <image src="test/taking_back.png" mode="widthFix" bindtap="cancelPhoto" wx:if="{{btnShow}}"></image>
  </view>
</view>

wxss代码:

.camera_box{height: 100vh;width: 100vw}
.camera_box .camera{height: 60vh;width: 100vw;z-index: 1}
.camera_box .cover_view{height: 60vh;width: 100vw;z-index: 999;display: flex}
.camera_box .cover_view .cover_legend{width: 90%;height: 430rpx;margin: auto}
.camera_box .camera_thumb{height: 60vh;width: 100%}
.camera_box .camera_btn{height: 40vh;display: flex;justify-content: space-around;align-items: center;background: rgba(0, 0, 0, .5);}
.camera_box .camera_btn image{width: 120rpx;}

js代码:

Page({

  /**
   * 页面的初始数据
   */
  data: {
    idCardUrl: '',
    btnShow: false
  },

  /**
   * 取消
   */
  cancelPhoto () {
    this.setData({
      btnShow: false,
      idCardUrl: ''
    })
  },
  
  /**
   * 保存
   */
  savePhoto(){
    wx.showModal({
      title: '图片地址',
      content: this.data.idCardUrl
    })
  },
  
  /**
   * 拍照
   */
  takeingPhoto() {
    const ctx = wx.createCameraContext();
    const listener = ctx.onCameraFrame();
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          idCardUrl: res.tempImagePath,
          btnShow: true
        })
        listener.stop({
          success: (res) => {
            console.log(res)
          },
          fail: (err) =>{
            console.log(err)
          }
        })
      },fail: (err) => {
        console.log(err)
      }
    })
  }
  
})

图片资源相关链接:
https://pan.baidu.com/s/15TIvEPGaG6WkQOhjFMJaLg

提取码:gdzl
解压密码:www.yangbike.com

已自动关闭评论