html5-qrcode实现扫二维码

html5-qrcode实现扫二维码

官方文档地址:https://www.npmjs.com/package/html5-qrcode
本地测试时候,在电脑端和苹果手机可以成功调用摄像头,但是在安卓端,无法调取,提示Camera access is only supported in secure context like https or localhost【仅在 https 或 localhost 等安全上下文中支持摄像头访问】,待解决

  • 首先下载依赖npm i html5-qrcode
  • 在扫码页面加入元素<div id="reader" width="600px"></div>
  • 引入Html5Qrcode,import { Html5Qrcode } from "html5-qrcode"
  • 在方法中调用官方提供的方法
<div id="reader" width="600px"></div>

import { Html5Qrcode } from "html5-qrcode";


    getCameras() {
      Html5Qrcode.getCameras()
        .then((devices) => {
          /**
           * devices would be an array of objects of type:
           * { id: "id", label: "label" }
           */
          if (devices && devices.length) {
            // 如果有2个摄像头,1为前置的
            if (devices.length > 1) {
              this.cameraId = devices[1].id;
            } else {
              this.cameraId = devices[0].id;
            }
            this.devices = devices;
            this.start();
            // .. use this to start scanning.
          }
        })
        .catch((err) => {
          // handle err
          console.log(err);    // 获取设备信息失败
        });
    },
    start() {
      const html5QrCode = new Html5Qrcode("reader");
      html5QrCode
        .start(
          this.cameraId, // retreived in the previous step.
          {
            fps: 10, // sets the framerate to 10 frame per second
            qrbox: { width: 250, height: 250 }, // sets only 250 X 250 region of viewfinder to
            // scannable, rest shaded.
          },
          (decodedText, decodedResult) => {
            // do something when code is read. For example:
            // if (qrCodeMessage) {
            //   this.getCode(qrCodeMessage);
            //   this.stop();
            // }
            console.log(decodedText); 
            console.log(decodedResult);
          },
          (errorMessage) => {
            // parse error, ideally ignore it. For example:
            // console.log(`QR Code no longer in front of camera.`);
            console.log(errorMessage); 
          }
        )
        .catch((err) => {
          // Start failed, handle it. For example,
          console.log(`Unable to start scanning, error: ${err}`);
        });
    },
    stop() {
      this.html5QrCode
        .stop()
        .then((ignore) => {
          // QR Code scanning is stopped.
          console.log("QR Code scanning stopped.");
        })
        .catch((err) => {
          // Stop failed, handle it.
          console.log("Unable to stop scanning.");
        });
    },
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容