Change orientation of the camera is based on the device’s orientation.

async function startCamera() {
    try {
        // Stop the previous stream if it exists
        if (videoStream) {
            const tracks = videoStream.getTracks();
            tracks.forEach(track => track.stop());
        }


        // Start a new video stream with the specified aspect ratio
        videoStream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode: 'environment', aspectRatio: 16 / 9 },
            audio: false
        });


        // Display the video feed
        const cameraFeed = document.getElementById('cameraFeed');
        cameraFeed.style.display = "inline";
        cameraFeed.style.height = "60%";
        cameraFeed.style.width = "50%";
        cameraFeed.srcObject = videoStream;


        cameraFeed.onloadedmetadata = () => {
            // Update the canvas dimensions
            const videoSettings = videoStream.getVideoTracks()[0].getSettings();
            console.log(Video settings: ${JSON.stringify(videoSettings)});
            canvas.width = videoSettings.width;
            canvas.height = videoSettings.height;
        };


        // Enable/disable buttons as needed
        document.getElementById('captureButton').disabled = false;
        document.getElementById('startCameraButton').disabled = true;
    } catch (error) {
        console.log("Error accessing camera: ", error);
    }
}


async function imageCapture() {
    console.log("start camera");


    const orientation = screen.orientation || screen.mozOrientation || screen.msOrientation;
    console.log("Device orientation: ", orientation.type);


    let aspectRatio;
    if (orientation.type === 'landscape-primary' || orientation.type === 'landscape-secondary') {
        aspectRatio = 16 / 9;
    } else if (orientation.type === 'portrait-primary' || orientation.type === 'portrait-secondary') {
        aspectRatio = 9 / 16;
    }


    await startCamera();
    window.addEventListener('orientationchange', async function () {
        await startCamera();
    });


}


async function stopCamera() {
    if (videoStream) {
        videoStream.getTracks().forEach(track => track.stop());
        document.getElementById('cameraFeed').srcObject = null;
        document.getElementById('cameraFeed').style.display = 'none';
    }
}


function captureImage() {
    context.drawImage(document.getElementById('cameraFeed'), 0, 0, canvas.width, canvas.height);
    document.getElementById('capturedImage').src = canvas.toDataURL('image/jpeg', 0.9);
    document.getElementById('retakeButton').style.display = 'inline';
    stopCamera();
    document.getElementById('captureButton').disabled = true;
    document.getElementById('startCameraButton').disabled = true;
    document.getElementById('uploadButton').disabled = false;
}


Leave a comment

Your email address will not be published. Required fields are marked *