小程序中调用摄像头修改成圆形样式并上传图片

在这里插入图片描述

所需资源地址:https://download.csdn.net/download/lb1135909273/12266605
这个下载所需的东西越来越。。。
这里给出百度云:
链接:https://pan.baidu.com/s/1Hp0zwf2b45mryuzYp48Tzg
提取码:b9qu

<view class="takephoto">
  <navigator open-type="navigateBack" hover-class="none" class="goBack">取消</navigator>
  <view class="distinguishing">
    <image src="../../../source/img/distinguishing.png" />
  </view>
  <view class="camera">
    <canvas class="progress_bg" canvas-id="canvasProgressbg"></canvas>
    <canvas class="progress_canvas" canvas-id="canvasProgress"></canvas>
    <camera id='camera' device-position="front" bindinitdone="startdrawCanvas" flash="off" binderror="error">
      <cover-view class='cameraGai'>
        <cover-image src='../../../source/img/circle.png' class='cover-image'></cover-image>
      </cover-view>
    </camera>
  </view>
  <view class="complete" bindtap="complateDis" wx:if="{{complete}}">完成</view>
  <i-message id="message" />
</view>

其实小程序的方形摄像头是不能改变的,所以我使用了一张圆形的图片,吧方形的框给遮住了,来实现这个效果

/* pages/takephoto/takephoto.wxss */
.takephoto{
  width: 100%;
}

.takephoto .camera{
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.takephoto camera {
  width: 220px;
  height: 220px;
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: -99;
}

.takephoto .goBack {
  color: #1792f0;
  margin-left: 35rpx;
  font-size: 35rpx;
}

.distinguishing image{
  height: 370rpx;
  width: 100%;
}

.progress_bg {
  position: absolute;
  width: 220px;
  height: 220px;
}

.progress_canvas {
  width: 220px;
  height: 220px;
}

.takephoto .complete {
  border-top: 1rpx solid #e5e5e5;
  width: 100%;
  position: fixed;
  bottom: 0;
  background: #fff;
  color: #1792f0;
  font-size: 40rpx;
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
}

并且用canvas画布做了一个2秒倒计时的圆形框。呈现一个动态获取视频的效果。其中canvas的用法和在普通H5用法一致。也引入了iview weapp的组件,提示用户跳转信息。为了方便将图片转化成了base64编码直接将编码上传。

// pages/takephoto/takephoto.js
import wxRequest from '../../../utils/wxRequest'
import regeneratorRuntime from '../../../utils/regenerator'
const { $Message } = require('../../../dist/base/index');

Page({
    /**
     * 页面的初始数据
     */
    data: {
        count: 0, // 设置 计数器 初始为0
        countTimer: null, // 设置 定时器 初始为null
        complete: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
    
    },
    onReady: function () {
      if (wx.createCameraContext()) {
        this.cameraContext = wx.createCameraContext('myCamera')
        this.drawProgressbg();
        // this.drawCircle();
        this.countInterval();
      } else {
        // 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
        wx.showModal({
          title: '提示',
          content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
        })
      }
      // this.bindChooiceProduct()
    },
    takePhoto() {
        const ctx = wx.createCameraContext()
        var that = this
        ctx.takePhoto({
            quality: 'high',
            success: (res) => {
                console.log(res.tempImagePath)
                var imgbase64Url = wx.getFileSystemManager().readFileSync(res.tempImagePath, "base64");
                // data:image/png;base64,
                // console.log(imgbase64Url)
                // that.uploadImg(encodeURIComponent(imgbase64Url))
                // 识别成功之后跳转
                $Message({
                  content: '正在识别,请稍后......',
                  type: 'success'
                });
                setTimeout(function () {
                  wx.navigateTo({
                    url: '../completeFetch/completeFetch'
                  })
                }, 2000)
            }
        })
    },
    error(e) {
        console.log(e.detail)
    },
    startdrawCanvas(){
      console.log('相机初始化成功')
    },
    //添加Banner  
    bindChooiceProduct: function () {
      var that = this;
      wx.chooseImage({
        count: 3, //最多可以选择的图片总数  
        sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有  
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有  
        success: function (res) {
          // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片  
          var tempFilePaths = res.tempFilePaths;
          console.log(tempFilePaths)
          //启动上传等待中...  
          var url = wx.getFileSystemManager().readFileSync(tempFilePaths[0], "base64")
          console.log(encodeURIComponent(url))
          that.uploadImg(encodeURIComponent(url))
        }
      });
    },
    async uploadImg(url){
      var res = await wxRequest.post('http://******/face/byte/api/search?imgByte=' + url, {
        imgByte: url
      })
      console.log(res)
      if(res.code == 200){
        if (res.data.faceMsg == 'pic not has face'){
          this.goBack('未捕获到人脸,请重新录入!')
        } else if (res.data.faceMsg == 'liveness check fail') {
          this.goBack('人脸匹配失败,请重新录入!')
        } else {
          $Message({
            content: '正在跳转',
            type: 'success'
          });
          wx.navigateTo({
            url: '../completeFetch/completeFetch'
          })
        }
      }else{
        this.goBack('网络错误,请重新录入!')
      }
    },
    goBack(info){
      $Message({
        content: info,
        type: 'error'
      });
      setTimeout(function(){
        wx.navigateBack();
      },2000)
    },
    drawProgressbg: function () {
      // 使用 wx.createContext 获取绘图上下文 context
      var ctx = wx.createCanvasContext('canvasProgressbg')
      ctx.setLineWidth(5); // 设置圆环的宽度
      ctx.setStrokeStyle('#a9a9a9'); // 设置圆环的颜色
      ctx.setLineCap('round') // 设置圆环端点的形状
      ctx.beginPath(); //开始一个新的路径
      ctx.arc(110, 110, 100, 0, 2 * Math.PI, false);
      //设置一个原点(100,100),半径为90的圆的路径到当前路径
      ctx.stroke(); //对当前路径进行描边
      ctx.draw();
    },
    drawCircle: function (step) {
      var context = wx.createCanvasContext('canvasProgress');
      // 设置渐变
      var gradient = context.createLinearGradient(200, 100, 100, 200);
      gradient.addColorStop("0", "#2661DD");
      gradient.addColorStop("0.5", "#2661DD");
      gradient.addColorStop("1.0", "#2661DD");
      context.setLineWidth(5);
      context.setStrokeStyle(gradient);
      context.setLineCap('round')
      context.beginPath();
      // 参数step 为绘制的圆环周长,从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ,结束角 通过改变 step 的值确定
      context.arc(110, 110, 100, -Math.PI / 2, step * Math.PI - Math.PI / 2, false);
      context.stroke();
      context.draw()
    },
    countInterval: function () {
      // 设置倒计时 定时器 每100毫秒执行一次,计数器count+1 ,耗时6秒绘一圈
      this.countTimer = setInterval(() => {
        if (this.data.count <= 60) {
          /* 绘制彩色圆环进度条
          注意此处 传参 step 取值范围是0到2,
          所以 计数器 最大值 60 对应 2 做处理,计数器count=60的时候step=2
          */
          this.drawCircle(this.data.count / (60 / 2))
          this.data.count++;
        } else {
          this.setData({
            complete: true
          });
          clearInterval(this.countTimer);
        }
      }, 100)
    },
    complateDis(){
      this.takePhoto()
    }
})
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值