Home Top Ad

Capture Photo using HTML and JavaScript Canvas tag | Capture Photo from Mobile or Webcam using JavaScript

As you know sometimes we need requirement to Capture a picture live cam rather than upload it from the file system. So in that case you can use this.


 It is too easy step you need to follow.


<button id="startCamera">Start The Camera</button>

<video id="video" width="320" height="240" autoplay></video>

<button id="click-photo">Take Photo</button>

<canvas id="canvas" width="320" height="240"></canvas>


<script>

    let camera_button = document.querySelector("#startCamera");

    let video = document.querySelector("#video");

    let click_button = document.querySelector("#click-photo");

    let canvas = document.querySelector("#canvas");


    camera_button.addEventListener('click', async function () {

        let stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });

        video.srcObject = stream;

    });


    click_button.addEventListener('click', function () {

        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);

        let image_data_url = canvas.toDataURL('image/jpeg');

        console.log(image_data_url);

    });

</script>


That's it you can test with till now.


If  you want to enhance more then use the below code to set the Camera Resolution


<button id="startCamera">Start Camera</button>

<script>

document.querySelector("#startCamera").addEventListener('click', async function() {
    let constraints = { 
                        audio: true, 
                        video: { 
                            width: { ideal: 1920 }, 
                            height: { ideal: 1080 } 
                        }
                    };

    let stream = await navigator.mediaDevices.getUserMedia(constraints);

    let stream_settings = stream.getVideoTracks()[0].getSettings();

    //its actual width and height of the camera video
    let stream_width = stream_settings.width;
    let stream_height = stream_settings.height;

    console.log('Width: ' + stream_width + 'px');
    console.log('Height: ' + stream_height + 'px');
});

</script>

Capture Photo using HTML and JavaScript Canvas tag | Capture Photo from Mobile or Webcam using JavaScript Capture Photo using HTML and JavaScript Canvas tag | Capture Photo from Mobile or Webcam using JavaScript Reviewed by Code Infosys on August 28, 2023 Rating: 5

Why you are not purchase ,At least Write in comment.

No comments