備忘錄_20160105(定位) 修改 回首頁

程式 2024-10-22 16:58:02 1729587483 100
從網路攝影機讀取QRCODE

從網路攝影機讀取QRCODE
執行看看
<!doctype html>
<html lang="zh-Hant-TW">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>QR Code Scanner From Webcam</title>
    <style>
      
      #myVideo
      {
        width: 300px;
        height: 200px;
        border: 1px solid black;
      }
      
    </style>
  </head>
  <body>
    <div>引用 https://github.com/cozmo/jsQR/blob/master/dist/jsQR.js</div>
    <div>純粹 JavaScript 解碼 QRCode</div>
    <br>
    <h1>QR Code Scanner with Webcam</h1>
    <video id="myVideo" autoplay playsinline></video>
    <p id="pResult">Waiting for QR Code...</p>
    <textarea id="ta1" rows="20" cols="80"></textarea>

    <!-- <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js"></script> -->
    <script src="jsQR.js"></script>
    <script>
      
      const oVideo = document.getElementById('myVideo');
      const pResultElement = document.getElementById('pResult');
      var strLastCode="";

      // 獲取使用者的攝像頭
      navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } })
        .then(
          function(oStream)
          {
            oVideo.srcObject = oStream;
            oVideo.play();
            window.requestAnimationFrame(processOneFrame);
          })
        .catch(
          function(oErr)
          {
            console.error('Error accessing webcam: ', oErr);
          });

      function processOneFrame()
      {
        if(oVideo.readyState===oVideo.HAVE_ENOUGH_DATA)
        {
          // 建立 canvas 用於獲取影像數據
          const oCanvas = document.createElement('canvas');
          const oCtx = oCanvas.getContext('2d');
          oCanvas.width = oVideo.videoWidth;
          oCanvas.height = oVideo.videoHeight;
          oCtx.drawImage(oVideo, 0, 0, oCanvas.width, oCanvas.height);

          // 從 oCanvas 中獲取影像數據
          const oImageData = oCtx.getImageData(0, 0, oCanvas.width, oCanvas.height);
          const oCode = jsQR(oImageData.data, oCanvas.width, oCanvas.height);

          if(oCode)
          {
            pResultElement.textContent = 'QR Code 內容: ' + oCode.data;
            pResultElement.style.color = 'green';
            
            if(oCode.data!=strLastCode)
            {
              strLastCode=oCode.data;
              document.getElementById("ta1").value
                =oCode.data+"\r\n"
                +document.getElementById("ta1").value;
            }
          }
          else
          {
            pResultElement.textContent = 'No QR Code detected.';
            pResultElement.style.color = 'red';
          }
        }
        
        // 繼續下一幀的掃描
        window.requestAnimationFrame(processOneFrame);
      }
    </script>
  </body>
</html>