Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Camera Recording and QR Code Scanning with HTML5 APIs

Tech 4

Accessing Camera and Recording Video in HTML5

To capture video from a camera and record it in a web application, use the getUserMedia and MediaRecorder APIs. Below is an example implementation.

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Camera Recording Demo</title>
    <style>
        .video-container {
            width: 100%;
            max-width: 600px;
            margin: 0 auto;
        }
        video {
            width: 100%;
            height: auto;
            border: 1px solid #ccc;
        }
        .controls {
            margin-top: 10px;
        }
        button {
            padding: 10px 15px;
            margin: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="video-container">
        <h2>Live Camera Feed</h2>
        <video id="liveFeed" autoplay></video>
        <h2>Recorded Playback</h2>
        <video id="playback" controls></video>
        <div class="controls">
            <button id="recordBtn">Start Recording</button>
            <button id="stopBtn">Stop Recording</button>
            <button id="captureBtn">Capture Photo</button>
        </div>
        <canvas id="photoCanvas" style="display:none;"></canvas>
    </div>

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

JavaScript Implementation

Create a file named script.js with the followign code:

// DOM element references
const liveVideo = document.getElementById('liveFeed');
const playbackVideo = document.getElementById('playback');
const recordButton = document.getElementById('recordBtn');
const stopButton = document.getElementById('stopBtn');
const captureButton = document.getElementById('captureBtn');
const photoCanvas = document.getElementById('photoCanvas');

// Media constraints for camera access
const mediaOptions = {
    video: {
        facingMode: { exact: "environment" }, // Use rear camera
        width: { ideal: 1280, max: 1920 },
        height: { ideal: 720, max: 1080 },
        frameRate: { ideal: 30, max: 45 }
    },
    audio: {
        sampleRate: 44100,
        sampleSize: 16,
        echoCancellation: true,
        noiseSuppression: true,
        autoGainControl: true
    }
};

let recorder;
let videoSegments = [];
let captureInterval;

// Initialize camera stream
navigator.mediaDevices.getUserMedia(mediaOptions)
    .then(stream => {
        liveVideo.srcObject = stream;
        recorder = new MediaRecorder(stream);

        recorder.ondataavailable = event => {
            if (event.data.size > 0) {
                videoSegments.push(event.data);
            }
        };

        recorder.onstop = () => {
            const videoBlob = new Blob(videoSegments, { type: 'video/webm' });
            playbackVideo.src = URL.createObjectURL(videoBlob);
            liveVideo.pause();
            playbackVideo.play();
        };
    })
    .catch(error => {
        console.error('Camera access failed:', error);
    });

// Event listeners for recording controls
recordButton.addEventListener('click', () => {
    videoSegments = [];
    liveVideo.play();
    recorder.start();
    captureInterval = setInterval(captureImage, 1000); // Capture image every second
});

stopButton.addEventListener('click', () => {
    clearInterval(captureInterval);
    recorder.stop();
});

// Function to capture a photo from the video stream
function captureImage() {
    photoCanvas.width = liveVideo.videoWidth;
    photoCanvas.height = liveVideo.videoHeight;
    const context = photoCanvas.getContext('2d');
    context.drawImage(liveVideo, 0, 0);
    // Optionally save or display the image
    console.log('Photo captured');
}

captureButton.addEventListener('click', captureImage);

Integrating QR Code Scaninng in HTML5

For QR code scanning, use a library like html5-qrcode. This example demonstrates basic integration.

HTML Setup

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QR Scanner Demo</title>
    <style>
        #scanner {
            width: 100%;
            max-width: 500px;
            margin: 20px auto;
        }
        #results {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body>
    <h1>QR Code Scanner</h1>
    <div id="scanner"></div>
    <div id="results"></div>

    <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
    <script src="scanner.js"></script>
</body>
</html>

JavaScript for Scanning

Create scanner.js:

const scannerElement = document.getElementById('scanner');
const resultsElement = document.getElementById('results');
let previousScan = '';
let scanCount = 0;

function handleScan(decodedData) {
    if (decodedData !== previousScan) {
        scanCount++;
        previousScan = decodedData;
        resultsElement.innerHTML = `<p>Scan #${scanCount}: ${decodedData}</p>`;
        console.log('Scanned data:', decodedData);
        // Add custom logic here, e.g., redirect or process data
    }
}

const qrScanner = new Html5QrcodeScanner(
    'scanner', 
    { 
        fps: 10, 
        qrbox: { width: 250, height: 250 } 
    }
);

qrScanner.render(handleScan);

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.