Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js"></script>
</head>
<body>
<h1>QR CODE SCANNER</h1>
<video id="video" width="640" height="480" style="display: none"></video>
<canvas id="canvas" width="640" height="480"></canvas>
<div id="output"></div>
<script>
const video = document.createElement("video");
const canvasElement = document.getElementById("canvas");
const canvas = canvasElement.getContext("2d");
const output = document.getElementById("output");
navigator.mediaDevices
.getUserMedia({ video: { facingMode: "environment" } })
.then(function (stream) {
video.srcObject = stream;
video.setAttribute("playsinline", true); // required to tell iOS safari we don't want fullscreen
video.play();
requestAnimationFrame(tick);
});
function tick() {
if (video.readyState === video.HAVE_ENOUGH_DATA) {
canvasElement.hidden = false;
canvasElement.height = video.videoHeight;
canvasElement.width = video.videoWidth;
canvas.drawImage(
video,
0,
0,
canvasElement.width,
canvasElement.height
);
const imageData = canvas.getImageData(
0,
0,
canvasElement.width,
canvasElement.height
);
const code = jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: "dontInvert",
});
// check if a QR code was detected,
// if there is one, display the value using the code.data property
if (code) {
output.innerText = `QR Code Value: ${code.data}`;
console.log("QR Code detected:", code.data);
} else {
console.log("No QR code detected.");
}
}
requestAnimationFrame(tick);
}
</script>
</body>
</html>
No comments:
Post a Comment