Created
May 16, 2025 17:04
-
-
Save marsz/23f8804b0f379b247eb37c7bd03e9cb6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <title>QR Code 掃描導向</title> | |
| <style> | |
| video { | |
| width: 100%; | |
| max-width: 480px; | |
| border: 1px solid #ccc; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <h2>請將 QR Code 對準鏡頭</h2> | |
| <video id="preview" autoplay></video> | |
| <script src="https://unpkg.com/jsqr/dist/jsQR.js"></script> | |
| <script> | |
| const video = document.getElementById('preview'); | |
| const canvas = document.createElement('canvas'); | |
| const ctx = canvas.getContext('2d'); | |
| async function startCamera() { | |
| try { | |
| const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } }); | |
| video.srcObject = stream; | |
| requestAnimationFrame(tick); | |
| } catch (err) { | |
| alert('無法開啟相機:' + err.message); | |
| } | |
| } | |
| function tick() { | |
| if (video.readyState === video.HAVE_ENOUGH_DATA) { | |
| canvas.width = video.videoWidth; | |
| canvas.height = video.videoHeight; | |
| ctx.drawImage(video, 0, 0, canvas.width, canvas.height); | |
| const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); | |
| const code = jsQR(imageData.data, canvas.width, canvas.height); | |
| if (code && code.data.startsWith('http')) { | |
| console.log('偵測到 QR Code:', code.data); | |
| video.srcObject.getTracks().forEach(track => track.stop()); // 停止鏡頭 | |
| location.href = code.data; // 導向網址 | |
| return; | |
| } | |
| } | |
| requestAnimationFrame(tick); | |
| } | |
| startCamera(); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment