小程序

html5-qrcode实现扫二维码

2022-03-04  本文已影响0人  萤火kin

html5-qrcode实现扫二维码

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

<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.");
        });
    },
上一篇下一篇

猜你喜欢

热点阅读