如何在 JS 中使用 ZXing 从网络摄像头扫描二维码?

How can I scan a QR code from a webcam using ZXing in JS?

我无法在主存储库上设置 README examples 之后的库。我不想使用 ES6、AMD 或任何需要构建步骤的方法。

您可以从 CDN 获取最新版本的库:

<script type="text/javascript" src="https://unpkg.com/@zxing/library@latest"></script>

有了它,ZXing 将在网页中可用,因此您可以使用类似这样的代码使用 decodeFromVideoDevice 方法从网络摄像头进行扫描:

<video id="webcam-preview"></video>
<p id="result"></p>
<script>
  const codeReader = new ZXing.BrowserQRCodeReader();

  codeReader.decodeFromVideoDevice(null, 'webcam-preview', (result, err) => {
    if (result) {
      // properly decoded qr code
      console.log('Found QR code!', result)
      document.getElementById('result').textContent = result.text
    }

    if (err) {
      // As long as this error belongs into one of the following categories
      // the code reader is going to continue as excepted. Any other error
      // will stop the decoding loop.
      //
      // Excepted Exceptions:
      //
      //  - NotFoundException
      //  - ChecksumException
      //  - FormatException

      if (err instanceof ZXing.NotFoundException) {
        console.log('No QR code found.')
      }

      if (err instanceof ZXing.ChecksumException) {
        console.log('A code was found, but it\'s read value was not valid.')
      }

      if (err instanceof ZXing.FormatException) {
        console.log('A code was found, but it was in a invalid format.')
      }
    }
  })
</script>

此代码将持续扫描网络摄像头视频流并尝试识别其中的二维码。