h5实现微信扫码

2,072 阅读1分钟

demo地址:https://fastcreator.github.io/qrcodeScan/dist/index.html

扫码访问


源码地址:https://github.com/fastCreator/qrcodeScan




编码过程

  1. 使用webpack打包,开发项目,webpack-dev-server进行本地开发调试
  2. 根据微信页面,书写html和css(less书写,更为便捷)
  3. 构思整个运行流程,书写交互逻辑


API调用

  1. //访问用户媒体设备的兼容方法function getUserMedia(constrains, success) { let error = (err) => { console.error('API:getUserMedia,' + err) } if (navigator.mediaDevices.getUserMedia) { //最新标准API navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error); } else if (navigator.webkitGetUserMedia) { //webkit内核浏览器 navigator.webkitGetUserMedia(constrains).then(success).catch(error); } else if (navigator.mozGetUserMedia) { //Firefox浏览器 navagator.mozGetUserMedia(constrains).then(success).catch(error); } else if (navigator.getUserMedia) { //旧版API navigator.getUserMedia(constrains).then(success).catch(error); }}
  2. //兼容性获取视频流配置项async function getConstraints() { const constraints = { audio: false, video: { width: { max: 400 }, height: { max: 280 } // facingMode: { exact: "environment" } //标准写法 } }; //获取设备信息,并且找出摄像头1,为后置摄像头 let devices = await navigator.mediaDevices.enumerateDevices() let videoinput = devices.filter(it => it.kind === 'videoinput') if (videoinput[1]) { constraints.video.deviceId = { exact: videoinput[1].deviceId || videoinput[0].deviceId } } return constraints}