JSFiddle - React, Tailwind, and code Playground

by ChangJoo Park

HTML

<video id="videoElement"></video>

JavaScript

const video = document.getElementById('videoElement');
console.log(video)
// Check if the browser supports media devices
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    // Access the webcam
    navigator.mediaDevices.getUserMedia({ video: true })
        .then((stream) => {
            // Set the video source to the webcam stream
            video.srcObject = stream;

            // When the video metadata is loaded
            video.onloadedmetadata = () => {
                // Calculate the aspect ratio of the video
                const aspectRatio = video.videoWidth / video.videoHeight;

                // Rotate the video element to portrait mode
                video.style.transform = 'rotate(90deg)';
                video.style.transformOrigin = 'center center';

                // Set the video dimensions to fill the screen
                if (window.innerWidth / window.innerHeight > aspectRatio) {
                    video.style.width = '100%';
                    video.style.height = 'auto';
                } else {
                    video.style.width = 'auto';
                    video.style.height = '100%';
                }
            };

            // Play the video
            video.play();
        })
        .catch((error) => {
            console.error('Error accessing the webcam:', error);
        });
} else {
    console.error('getUserMedia is not supported by this browser');
}