QR Code Scanner

HTML

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>QR Code Scanner</title>

    <link rel="stylesheet" href="style.css">

</head>

<body>

    <div class="scanner-container">

        <video id="video" width="640" height="480" autoplay></video>

        <canvas id="canvas" width="640" height="480"></canvas>

        <button id="start-button">Start Scanning</button>

        <div id="result"></div>

    </div>


    <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.1/dist/jsQR.js"></script>

    <script src="script.js"></script>

</body>

</html>


CSS

.scanner-container {

    display: flex;

    flex-direction: column;

    align-items: center;

    padding: 20px;

    background-color: #f0f0f0;

    border: 1px solid #ddd;

    border-radius: 10px;

    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

}


#video {

    border: 1px solid black;

    border-radius: 10px;

}


#canvas {

    display: none;

}


#result {

    margin-top: 20px;

    font-size: 24px;

    font-weight: bold;

    color: #333;

}


#start-button {

    background-color: #4CAF50;

    color: #fff;

    padding: 10px 20px;

    border: none;

    border-radius: 10px;

    cursor: pointer;

}


#start-button:hover {

    background-color: #3e8e41;

}

Js

const video = document.getElementById('video');

const canvas = document.getElementById('canvas');

const startButton = document.getElementById('start-button');

const resultDiv = document.getElementById('result');


startButton.addEventListener('click', async () => {

    try {

        const stream = await navigator.mediaDevices.getUserMedia({

            video: {

                facingMode: 'environment',

                width: 640,

                height: 480

            }

        });


        video.srcObject = stream;

        video.play();


        video.addEventListener('play', () => {

            canvas.getContext('2d').drawImage(video, 0, 0, 640, 480);

            const imageData = canvas.getContext('2d').getImageData(0, 0, 640, 480);

            const code = jsQR(imageData.data, imageData.width, imageData.height);

            if (code) {

                resultDiv.innerText = code.data;

            }

        });

    } catch (error) {

        console.error(error);

    }

});


window.addEventListener('beforeunload', () => {

    video.srcObject.getTracks().forEach(track => track.stop());

});