JSFiddle - React, Tailwind, and code Playground
by Rapha Souza
HTML
<html>
<head>
<title>QR Code Scanner</title>
</head>
<body>
<video id=”camera feed” width=”320" height=”240" autoplay></video>
<script src=”https://cdn.rawgit.com/cozmo/jsQR/master/dist/jsQR.js"></script>
<script>
async function initCamera() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: { facing mode: ‘environment’ } });
const video = document.getElementById(‘cameraFeed’);
video.subject = stream;
scan QR code(stream);
} catch (error) {
console.error(‘Error accessing camera:’, error);
function scan QR code(stream) {
const video = document.getElementById(‘cameraFeed’);
const canvas = document.createElement(‘canvas’);
const context = canvas.getContext(‘2d’);
canvas.width = video.video width;
canvas.height = video.video height;
function scan() {
context.drawImage(video, 0, 0, canvas.width, canvas.height);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
console.log(‘QR Code detected:’, code.data);
// Perform desired actions with code.data (QR code information).
requestAnimationFrame(scan);
video.addEventListener(‘loaded metadata, () => {
scan();
// Close the camera stream when leaving the page.
window.addEventListener(‘before unload, () => {
stream.get tracks().forEach(track => track.stop());
initCamera();
</script>
</body>
</html>