Translate

2022年7月24日 星期日

掃瞄QRCODE

只靠 HTML 前端技術就可以使用相機,那麼最實用的功能就是掃瞄 QRCODE ,這裡提供一個最簡單易用的方式

使用函式庫:https://github.com/mebjas/html5-qrcode


  <button id="b072401_idfront">Front</button>
  <button id="b072401_idback">Back</button>
  <button id="b072401_idstop">Stop</button>
  <input type="file" id="b072401_idfile" accept="image/*">
  <hr>
  <div id="b072401_idresult"></div>
  <hr>
  <div id="b072401_reader" style="display:inline-block;width:320px;"></div>
  <script>
    $(function()
      {
      const html5QrCode = new Html5Qrcode("b072401_reader");
      const qrCodeSuccessCallback = (decodedText, decodedResult) => 
      {
        $("#b072401_idresult").html(JSON.stringify(decodedResult,"",4))
      };
      const config = 
            { 
              fps: 10, 
              qrbox: { width: 200, height: 200 } 
            };
      $("#b072401_idfront").on("click",function()
                               {
        $("#b072401_idstop").click();
        html5QrCode.start({ facingMode: "user" }, config, qrCodeSuccessCallback);
      })
      $("#b072401_idback").on("click",function()
                              {
        $("#b072401_idstop").click();
        html5QrCode.start({ facingMode: "environment" }, config, qrCodeSuccessCallback);
      })
      $("#b072401_idstop").on("click",function()
                              {
        try
        {
          html5QrCode.stop().then((ignore) => 
                                  {
            console.log("stop ok")
          }).catch((err) => {
            console.log("stop err")
          });
        }
        catch(e){}
      })
      $("#b072401_idfile").on("change",function(e)
                              {
        $("#b072401_idstop").click();
        if (e.target.files.length == 0) {
          // No file selected, ignore 
          return;
        }
        const imageFile = e.target.files[0];
        // Scan QR Code
        html5QrCode.scanFile(imageFile, true)
          .then((decodedText) => {
          $("#b072401_idresult").html(decodedText)
        })
          .catch(err => {
          console.log(`Error scanning file. Reason: ${err}`)
        });
      })
    })
  </script>
  <script src="https://yiharng.github.io/html5-qrcode.min.js"></script>


沒有留言:

張貼留言