DEV Community

Cover image for Live Stream your Webcam to HTML Page
Rohit Dalal
Rohit Dalal

Posted on

Live Stream your Webcam to HTML Page

Ever wondered how you can stream your own webcam recording live on HTML page?

Well, in this quick and easy post, we will have a look at how you can live to stream your webcam straight to your HTML page.

Let's get started.

Setup

HTML required for this short demo is a one-liner. Create a file index.html and paste the following:

<video id="myVidPlayer" controls muted autoplay></video>
Enter fullscreen mode Exit fullscreen mode

This embeds a Simple HTML5 video player to your page. controls muted autoplay are optional parameters to video tag, which clearly describe their purposes.

Now, it's time to add some life to the video player. This code will Stream your Webcam recording to the created video player

<script type="text/javascript">
    //Selector for your <video> element
    const video = document.querySelector('#myVidPlayer');

    //Core
    window.navigator.mediaDevices.getUserMedia({ video: true })
        .then(stream => {
            video.srcObject = stream;
            video.onloadedmetadata = (e) => {
                video.play();
            };
        })
        .catch( () => {
            alert('You have give browser the permission to run Webcam and mic ;( ');
        });

</script>
Enter fullscreen mode Exit fullscreen mode

Here, getUserMedia() is a function which needs an object as a parameter with either of audio/video as a compulsory property set to true. Else, you will get an error. This function then returns a Promise.

Upon running this code, the browser will ask for our permission for the usage of Microphone and Camera. If you "allow" it to use, then our Promise resolves with "stream" as a parameter which we assign it to video.srcObject. This sets the stage up for playing the video. Upon successful loading of metadata of our video player (video.onloadmetadata), we start the actual streaming with video.play() and you will see your "beautiful" face right there on your HTML page, else it is rejected with an alert box popup.

Bonus: Snapshot of the current video frame

Now, we will add a button which will get the snapshot of the current video frame on click and will display it to you in a canvas element.

<button onclick="snapshot()" >Snapshot</button>

<div class="mycanvas">
    <h6>Captured snapshot</h6>
    <canvas></canvas>
</div>
Enter fullscreen mode Exit fullscreen mode

Let's rewrite our complete JavaScript

<script type="text/javascript">
    var canvas = document.querySelector("canvas");
    var context = canvas.getContext("2d");
    const video = document.querySelector('#myVidPlayer');

    //w-width,h-height
    var w, h;
    canvas.style.display = "none";

    //new
    function snapshot(){
        context.fillRect(0, 0, w, h);
        context.drawImage(video, 0, 0, w, h);
        canvas.style.display = "block";
    }

    window.navigator.mediaDevices.getUserMedia({ video: true, audio: true })
        .then(stream => {
            video.srcObject = stream;
            video.onloadedmetadata = (e) => {
                video.play();

                //new
                w = video.videoWidth;
                h = video.videoHeight

                canvas.width = w;
                canvas.height = h;
            };
        })
        .catch(error => {
            alert('You have to enable the mike and the camera');
        });
</script>
Enter fullscreen mode Exit fullscreen mode

On clicking the button, canvas context is filled with a 2D rectangle with w=width and h=height. (0,0) is passed to tell that we want to fill the context from the left top corner of the canvas. Then, we attach our video frame snapshot to the canvas and make it visible with display: "block" which was hidden by default. More info on Canvas API is here.

Here is the Code pen link Codepen.

Conclusion

This was it for this short and sweet tutorial. See you next time ;)

Top comments (5)

Collapse
 
bravemaster619 profile image
bravemaster619

Great work! Keep going!

Collapse
 
dalalrohit profile image
Rohit Dalal

Thank you so much!

Collapse
 
hwolf0610 profile image
Harry Naruto

Thank you for your post.

Collapse
 
quantuminformation profile image
Nikos

You should make the link to CP target blank, also I just see 3 loading dots

Collapse
 
zillabunnies profile image
Zilla Bunny

This is really awesome!! When I stream tho only I can see it if anyone else goes to the website they get the prompt and don't see my video? how do I stream to others?