{"id":20057503,"url":"https://github.com/dragonir/h5-scan-qrcode","last_synced_at":"2025-04-09T13:05:09.314Z","repository":{"id":47608860,"uuid":"416158298","full_name":"dragonir/h5-scan-qrcode","owner":"dragonir","description":"📷 h5 scan qrcode 前端实现H5浏览器扫码功能","archived":false,"fork":false,"pushed_at":"2021-10-14T01:39:05.000Z","size":16692,"stargazers_count":288,"open_issues_count":7,"forks_count":88,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-04-02T11:05:11.797Z","etag":null,"topics":["camera","h5","javascript","qrcode","scanner"],"latest_commit_sha":null,"homepage":"https://dragonir.github.io/h5-scan-qrcode/","language":"Vue","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dragonir.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-10-12T02:43:20.000Z","updated_at":"2025-04-01T02:30:15.000Z","dependencies_parsed_at":"2022-09-13T12:41:09.345Z","dependency_job_id":null,"html_url":"https://github.com/dragonir/h5-scan-qrcode","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dragonir%2Fh5-scan-qrcode","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dragonir%2Fh5-scan-qrcode/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dragonir%2Fh5-scan-qrcode/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dragonir%2Fh5-scan-qrcode/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dragonir","download_url":"https://codeload.github.com/dragonir/h5-scan-qrcode/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248045230,"owners_count":21038553,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["camera","h5","javascript","qrcode","scanner"],"created_at":"2024-11-13T12:59:12.131Z","updated_at":"2025-04-09T13:05:09.283Z","avatar_url":"https://github.com/dragonir.png","language":"Vue","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n![](https://img2020.cnblogs.com/blog/772544/202110/772544-20211014085859146-787620276.png)\n\n## 背景\n\n不久前我做了关于获取浏览器摄像头并扫码识别的功能，本文中梳理了涉及到知识点及具体代码实现，整理成此篇文章内容。\n\n本文主要介绍，通过使用基于 `vue` 技术栈的前端开发技术，在浏览器端调起摄像头 `📷`，并进行扫码识别功能，对识别到的二维码进行跳转或其他操作处理。本文内容分为背景介绍、实现效果、技术简介、代码实现、总结等部分组成。\n\n## 实现效果\n\n本实例中主要有两个页面首页和扫码页，具体实现效果如下图所示。\n\n* 首页：点击 `SCAN QRCODE` 按钮，进入到扫码页。\n* 扫码页：首次进入时，或弹出 `获取摄像头访问权限的系统提示框`，点击允许访问，页面开始加载摄像头数据并开始进行二维码捕获拾取，若捕获到二维码，开始进行二维码解析，解析成功后加载识别成功弹窗。\n\n![](https://img2020.cnblogs.com/blog/772544/202110/772544-20211014085910878-405058356.gif)\n\n\u003e `📸` 在线体验：https://dragonir.github.io/h5-scan-qrcode\n\n![](https://img2020.cnblogs.com/blog/772544/202110/772544-20211014085936872-953138653.png)\n\n\n\u003e `📌` 提示：需要在有摄像头设备的浏览器中竖屏访问。手机横竖屏检测小知识可前往我的另一篇文章[《五十音小游戏中的前端知识》](https://juejin.cn/post/6987393152332070920) 中进行了解。\n\n## 技术简介\n\n### WebRTC API\n\n**WebRTC (Web Real-Time Communications) 是一项实时通讯技术**，它允许网络应用或者站点，在**不借助中间媒介**的情况下，建立浏览器之间 `点对点（Peer-to-Peer）` 的连接，实现视频流和（或）音频流或者其他任意数据的传输。`WebRTC` 包含的这些标准使用户在无需安装任何插件或者第三方的软件的情况下，创建 `点对点（Peer-to-Peer）` 的数据分享和电话会议成为可能。\n\n**三个主要接口**：\n* `MediaStream`：能够通过设备的摄像头及话筒获得视频、音频的同步流。\n* `RTCPeerConnection`：是 `WebRTC` 用于构建点对点之间稳定、高效的流传输的组件。\n* `RTCDataChannel`：使得浏览器之间建立一个高吞吐量、低延时的信道，用于传输任意数据。\n\n\u003e `🔗` 前往 `MDN` 深入学习：[WebRTC_API](https://developer.mozilla.org/zh-CN/docs/Web/API/WebRTC_API)\n\n### WebRTC adapter\n\n虽然 `WebRTC` 规范已经相对健全稳固了，但是并不是所有的浏览器都实现了它所有的功能，有些浏览器需要在一些或者所有的 `WebRTC API`上添加前缀才能正常使用。\n\n`WebRTC` 组织在 `github` 上提供了一个 `WebRTC适配器（WebRTC adapter）` 来解决在不同浏览器上实现 `WebRTC` 的兼容性问题。这个适配器是一个 `JavaScript垫片`，它可以让你根据 `WebRTC` 规范描述的那样去写代码，在所有支持 `WebRTC` 的浏览器中不用去写前缀或者其他兼容性解决方法。\n\n\u003e `🔗` 前往 `MDN` 深入学习：[WebRTC adapter](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/adapter.js)\n\n\n### 核心的API `navigator.mediaDevices.getUserMedia`\n\n网页调用摄像头需要调用 `getUserMedia API`，`MediaDevices.getUserMedia()` 会提示用户给予使用媒体输入的许可，媒体输入会产生一个 `MediaStream`，里面包含了请求的媒体类型的轨道。此流可以包含一个视频轨道（来自硬件或者虚拟视频源，比如相机、视频采集设备和屏幕共享服务等等）、一个音频轨道（同样来自硬件或虚拟音频源，比如麦克风、`A/D转换器` 等等），也可能是其它轨道类型。\n\n它返回一个 `Promise` 对象，成功后会 `resolve` 回调一个 `MediaStream对象`；若用户拒绝了使用权限，或者需要的媒体源不可用，`promise` 会 `reject` 回调一个 `PermissionDeniedError` 或者 `NotFoundError` 。(返回的 `promise对象` 可能既不会 `resolve` 也不会 `reject`，因为用户不是必须选择允许或拒绝。)\n\n通常可以使用 `navigator.mediaDevices` 来获取 `MediaDevices` ，例如：\n\n```js\nnavigator.mediaDevices.getUserMedia(constraints)\n  .then(function(stream) {\n    // 使用这个stream\n  })\n  .catch(function(err) {\n    // 处理error\n  })\n```\n\n\u003e `🔗` 前往 `MDN` 深入学习：[navigator.mediaDevices.getUserMedia](https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia)\n\n\n### 二维码解析库 `JSQR`\n\n`jsQR` 是一个纯 `JavaScript` 二维码解析库，该库读取原始图像或者是摄像头，并将定位，提取和解析其中的任何 `QR码`。\n\n如果要使用 `jsQR` 扫描网络摄像头流，则需要 `ImageData` 从视频流中提取，然后可以将其传递给 `jsQR`。\n\n`jsQR` 导出一个方法，该方法接受 `4` 个参数，分别是解码的 `图像数据`，`宽`、`高` 以及 `可选的对象` 进一步配置扫描行为。\n\n`imageData`：格式为 `[r0, g0, b0, a0, r1, g1, b1, a1, ...]` 的 `Uint8ClampedArray（ 8位无符号整型固定数组）` 的 `rgba` 像素值。\n\n```js\nconst code = jsQR(imageData, width, height, options);\nif (code) {\n  console.log('找到二维码！', code);\n}\n```\n\n\u003e `🔗` 前往 `github` 深入了解：[jsQR](https://github.com/cozmo/jsQR)\n\n\n## 代码实现\n\n### 流程\n\n整个扫码流程如下图所示：页面初始化，先检查浏览器是否支持 `mediaDevices` 相关`API`，浏览器进行调去摄像头，调用失败，就执行失败回调；调用成功，进行捕获视频流，然后进行扫码识别，没有扫瞄到可识别的二维码就继续扫描，扫码成功后绘制扫描成功图案并进行成功回调。\n\n![](https://img2020.cnblogs.com/blog/772544/202110/772544-20211014085958959-714223482.png)\n\n\n下文内容对流程进行拆分，分别实现对应的功能。\n\n### 扫码组件 `Scaner`\n\n#### 页面结构\n\n我们先看下页面结构，主要由 `4` 部分组成：\n\n* 提示框。\n* 扫码框。\n* `video`：展示摄像头捕获视频流。\n* `canvas`: 绘制视频帧，用于二维码识别。\n\n```html\n\u003ctemplate\u003e\n  \u003cdiv class=\"scaner\" ref=\"scaner\"\u003e\n    \u003c!-- 提示框：用于在不兼容的浏览器中显示提示语 --\u003e\n    \u003cdiv class=\"banner\" v-if=\"showBanner\"\u003e\n      \u003ci class=\"close_icon\" @click=\"() =\u003e showBanner = false\"\u003e\u003c/i\u003e\n      \u003cp class=\"text\"\u003e若当前浏览器无法扫码，请切换其他浏览器尝试\u003c/p\u003e\n    \u003c/div\u003e\n    \u003c!-- 扫码框：显示扫码动画 --\u003e\n    \u003cdiv class=\"cover\"\u003e\n      \u003cp class=\"line\"\u003e\u003c/p\u003e\n      \u003cspan class=\"square top left\"\u003e\u003c/span\u003e\n      \u003cspan class=\"square top right\"\u003e\u003c/span\u003e\n      \u003cspan class=\"square bottom right\"\u003e\u003c/span\u003e\n      \u003cspan class=\"square bottom left\"\u003e\u003c/span\u003e\n      \u003cp class=\"tips\"\u003e将二维码放入框内，即可自动扫描\u003c/p\u003e\n    \u003c/div\u003e\n    \u003c!-- 视频流显示 --\u003e\n    \u003cvideo\n      v-show=\"showPlay\"\n      class=\"source\"\n      ref=\"video\"\n      :width=\"videoWH.width\"\n      :height=\"videoWH.height\"\n      controls\n    \u003e\u003c/video\u003e\n    \u003ccanvas v-show=\"!showPlay\" ref=\"canvas\" /\u003e\n    \u003cbutton v-show=\"showPlay\" @click=\"run\"\u003e开始\u003c/button\u003e\n  \u003c/div\u003e\n\u003c/template\u003e\n```\n\n#### 方法：绘制\n\n* 画线。\n* 画框（用于扫码成功后绘制矩形图形)。\n\n![](https://img2020.cnblogs.com/blog/772544/202110/772544-20211014090011600-1539245730.png)\n\n```js\n// 画线\ndrawLine (begin, end) {\n  this.canvas.beginPath();\n  this.canvas.moveTo(begin.x, begin.y);\n  this.canvas.lineTo(end.x, end.y);\n  this.canvas.lineWidth = this.lineWidth;\n  this.canvas.strokeStyle = this.lineColor;\n  this.canvas.stroke();\n},\n// 画框\ndrawBox (location) {\n  if (this.drawOnfound) {\n    this.drawLine(location.topLeftCorner, location.topRightCorner);\n    this.drawLine(location.topRightCorner, location.bottomRightCorner);\n    this.drawLine(location.bottomRightCorner, location.bottomLeftCorner);\n    this.drawLine(location.bottomLeftCorner, location.topLeftCorner);\n  }\n},\n```\n\n#### 方法：初始化\n\n* 检查是否支持。\n* 调起摄像头。\n* 成功失败处理。\n\n![](https://img2020.cnblogs.com/blog/772544/202110/772544-20211014090024027-1700209609.png)\n\n```js\n// 初始化\nsetup () {\n  // 判断了浏览器是否支持挂载在MediaDevices.getUserMedia()的方法\n  if (navigator.mediaDevices \u0026\u0026 navigator.mediaDevices.getUserMedia) {\n    this.previousCode = null;\n    this.parity = 0;\n    this.active = true;\n    this.canvas = this.$refs.canvas.getContext(\"2d\");\n    // 获取摄像头模式，默认设置是后置摄像头\n    const facingMode = this.useBackCamera ? { exact: 'environment' } : 'user';\n    // 摄像头视频处理\n    const handleSuccess = stream =\u003e {\n       if (this.$refs.video.srcObject !== undefined) {\n        this.$refs.video.srcObject = stream;\n      } else if (window.videoEl.mozSrcObject !== undefined) {\n        this.$refs.video.mozSrcObject = stream;\n      } else if (window.URL.createObjectURL) {\n        this.$refs.video.src = window.URL.createObjectURL(stream);\n      } else if (window.webkitURL) {\n        this.$refs.video.src = window.webkitURL.createObjectURL(stream);\n      } else {\n        this.$refs.video.src = stream;\n      }\n      // 不希望用户来拖动进度条的话，可以直接使用playsinline属性，webkit-playsinline属性\n      this.$refs.video.playsInline = true;\n      const playPromise = this.$refs.video.play();\n      playPromise.catch(() =\u003e (this.showPlay = true));\n      // 视频开始播放时进行周期性扫码识别\n      playPromise.then(this.run);\n    };\n    // 捕获视频流\n    navigator.mediaDevices\n      .getUserMedia({ video: { facingMode } })\n      .then(handleSuccess)\n      .catch(() =\u003e {\n        navigator.mediaDevices\n          .getUserMedia({ video: true })\n          .then(handleSuccess)\n          .catch(error =\u003e {\n            this.$emit(\"error-captured\", error);\n          });\n      });\n  }\n},\n```\n\n#### 方法：周期性扫描\n\n![](https://img2020.cnblogs.com/blog/772544/202110/772544-20211014090035561-391179065.png)\n\n```js\nrun () {\n  if (this.active) {\n    // 浏览器在下次重绘前循环调用扫码方法\n    requestAnimationFrame(this.tick);\n  }\n},\n```\n\n#### 方法：成功回调\n\n![](https://img2020.cnblogs.com/blog/772544/202110/772544-20211014090047129-481119783.png)\n\n```js\n// 二维码识别成功事件处理\nfound (code) {\n  if (this.previousCode !== code) {\n    this.previousCode = code;\n  } else if (this.previousCode === code) {\n    this.parity += 1;\n  }\n  if (this.parity \u003e 2) {\n    this.active = this.stopOnScanned ? false : true;\n    this.parity = 0;\n    this.$emit(\"code-scanned\", code);\n  }\n},\n```\n\n#### 方法：停止\n\n![](https://img2020.cnblogs.com/blog/772544/202110/772544-20211014090058546-1649597403.png)\n\n```js\n\n// 完全停止\nfullStop () {\n  if (this.$refs.video \u0026\u0026 this.$refs.video.srcObject) {\n    // 停止视频流序列轨道\n    this.$refs.video.srcObject.getTracks().forEach(t =\u003e t.stop());\n  }\n}\n```\n\n#### 方法：扫描\n\n* 绘制视频帧。\n* 扫码识别。\n\n![](https://img2020.cnblogs.com/blog/772544/202110/772544-20211014090110046-1263690084.png)\n\n```js\n// 周期性扫码识别\ntick () {\n  // 视频处于准备阶段，并且已经加载足够的数据\n  if (this.$refs.video \u0026\u0026 this.$refs.video.readyState === this.$refs.video.HAVE_ENOUGH_DATA) {\n    // 开始在画布上绘制视频\n    this.$refs.canvas.height = this.videoWH.height;\n    this.$refs.canvas.width = this.videoWH.width;\n    this.canvas.drawImage(this.$refs.video, 0, 0, this.$refs.canvas.width, this.$refs.canvas.height);\n    // getImageData() 复制画布上制定矩形的像素数据\n    const imageData = this.canvas.getImageData(0, 0, this.$refs.canvas.width, this.$refs.canvas.height);\n    let code = false;\n    try {\n      // 识别二维码\n      code = jsQR(imageData.data, imageData.width, imageData.height);\n    } catch (e) {\n      console.error(e);\n    }\n    // 如果识别出二维码，绘制矩形框\n    if (code) {\n      this.drawBox(code.location);\n      // 识别成功事件处理\n      this.found(code.data);\n    }\n  }\n  this.run();\n},\n```\n\n### 父组件\n\n`Scaner` 的父组件主要加载页面，并展示 `Scaner` 扫码结果的回调。\n\n#### 页面结构\n\n```html\n\u003ctemplate\u003e\n  \u003cdiv class=\"scan\"\u003e\n    \u003c!-- 页面导航栏 --\u003e\n    \u003cdiv class=\"nav\"\u003e\n      \u003ca class=\"close\" @click=\"() =\u003e $router.go(-1)\"\u003e\u003c/a\u003e\n      \u003cp class=\"title\"\u003eScan QRcode\u003c/p\u003e\n    \u003c/div\u003e\n    \u003cdiv class=\"scroll-container\"\u003e\n      \u003c!-- 扫码子组件 --\u003e\n      \u003cScaner\n        v-on:code-scanned=\"codeScanned\"\n        v-on:error-captured=\"errorCaptured\"\n        :stop-on-scanned=\"true\"\n        :draw-on-found=\"true\"\n        :responsive=\"false\"\n      /\u003e\n    \u003c/div\u003e\n  \u003c/div\u003e\n\u003c/template\u003e\n```\n\n\n#### 父组件方法\n\n```js\nimport Scaner from '../components/Scaner';\n\nexport default {\n  name: 'Scan',\n  components: {\n    Scaner\n  },\n  data () {\n    return {\n      errorMessage: \"\",\n      scanned: \"\"\n    }\n  },\n  methods: {\n    codeScanned(code) {\n      this.scanned = code;\n      setTimeout(() =\u003e {\n        alert(`扫码解析成功: ${code}`);\n      }, 200)\n    },\n    errorCaptured(error) {\n      switch (error.name) {\n        case \"NotAllowedError\":\n          this.errorMessage = \"Camera permission denied.\";\n          break;\n        case \"NotFoundError\":\n          this.errorMessage = \"There is no connected camera.\";\n          break;\n        case \"NotSupportedError\":\n          this.errorMessage =\n            \"Seems like this page is served in non-secure context.\";\n          break;\n        case \"NotReadableError\":\n          this.errorMessage =\n            \"Couldn't access your camera. Is it already in use?\";\n          break;\n        case \"OverconstrainedError\":\n          this.errorMessage = \"Constraints don't match any installed camera.\";\n          break;\n        default:\n          this.errorMessage = \"UNKNOWN ERROR: \" + error.message;\n      }\n      console.error(this.errorMessage);\n     alert('相机调用失败');\n    }\n  },\n  mounted () {\n    var str = navigator.userAgent.toLowerCase();\n    var ver = str.match(/cpu iphone os (.*?) like mac os/);\n    // 经测试 iOS 10.3.3以下系统无法成功调用相机摄像头\n    if (ver \u0026\u0026 ver[1].replace(/_/g,\".\") \u003c '10.3.3') {\n     alert('相机调用失败');\n    }\n  }\n```\n\n### 完整代码\n\n\u003e `🔗` github: https://github.com/dragonir/h5-scan-qrcode\n\n\n## 总结\n\n### 应用扩展\n\n我觉得以下几个功能都是可以通过浏览器调用摄像头并扫描识别来实现的，大家觉得还有哪些 `很哇塞🌟` 的功能应用可以通过浏览器端扫码实现 `😂`？\n\n* `🌏` 链接跳转。\n* `🛒` 价格查询。\n* `🔒` 登录认证。\n* `📂` 文件下载。\n\n### 兼容性\n\n![](https://img2020.cnblogs.com/blog/772544/202110/772544-20211014090128398-30284042.png)\n\n* `❗` 即使使用了 `adapter`，`getUserMedia API` 在部分浏览器中也存在不支持的。\n* `❗` 低版本浏览器（如 `iOS 10.3` 以下）、`Android` 小众浏览器（如 `IQOO` 自带浏览器）不兼容。\n* `❗` `QQ`、`微信` 内置浏览器无法调用。\n\n### 参考资料\n\n* [1]. [Taking still photos with WebRTC](https://developer.mozilla.org/zh-CN/docs/Web/API/WebRTC_API/Taking_still_photos)\n* [2]. [Choosing cameras in JavaScript with the mediaDevices API](https://www.twilio.com/blog/2018/04/choosing-cameras-javascript-mediadevices-api.html)\n* [3]. [如何使用JavaScript访问设备前后摄像头](https://juejin.cn/post/6844904184643321870)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdragonir%2Fh5-scan-qrcode","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdragonir%2Fh5-scan-qrcode","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdragonir%2Fh5-scan-qrcode/lists"}