JavaScript实现识别二维码信息功能

首先,我们需要在HTML文件中引入jsQR库:

<script src="https://cdn.jsdelivr.net/npm/jsqr/dist/jsQR.js"></script>

接下来,我们需要一个文件输入框和一个按钮来触发扫描二维码的功能:

<input type="file" accept="image/*" capture="environment" id="fileInput" style="display: none;">
<button onclick="scanQRCode()">扫描二维码</button>

然后,我们编写JavaScript函数来实现扫描二维码的功能:

<script>
  function scanQRCode() {
    const fileInput = document.getElementById('fileInput');
    fileInput.click();

    fileInput.onchange = function() {
      const file = fileInput.files[0];
      const reader = new FileReader();

      reader.onload = function(e) {
        const img = new Image();

        img.src = e.target.result;
        img.onload = function() {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');

          canvas.width = img.width;
          canvas.height = img.height;
          ctx.drawImage(img, 0, 0, img.width, img.height);

          const imageData = ctx.getImageData(0, 0, img.width, img.height);
          const code = jsQR(imageData.data, imageData.width, imageData.height);
          if (code) {
            alert('扫描结果: ' + code.data);
          } else {
            alert('未识别到二维码');
          }
        };
      };
      reader.readAsDataURL(file);
    };
  }
</script>

原文链接:https://blog.csdn.net/m0_71966801/article/details/135539139