首页 > 解决方案 > 如何在 JS 中使用 ZXing 从网络摄像头扫描二维码?

问题描述

我无法设置库来跟踪主存储库上的README 示例。我不想使用 ES6、AMD 或任何需要构建步骤的方法。

标签: javascriptzxingzxing-js

解决方案


您可以从 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>

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


推荐阅读