How To Access WebCam in JavaScript



in this tutorial, I will show you how you can access your WebCam on your browser and displaying the output inside a video tag using javascript. it's pretty simple and you will not need any library to do this, so let's start coding.

HTML Code

first, we need to create an HTML Page where we will add a video tag that will display the webcam source video, to do this it's simple you only need to add a video tag using HTML 
like the code behind


<html>

<head>
    <title>Acces Webcam</title>
</head>

<body>
    <div class="wrapper">
        <video autoplay controls width="720" id="video"> </video>
    </div>
</body>
<script src="main.js"></script>

</html>

now let's focus on the most important part, JAVASCRIPT, so we will need to create a javascript file called "main.js" and let's start coding.
just copy and paste the following code and let me explain to you the most important lines


let streaming = document.getElementById("video");
navigator.mediaDevices.getUserMedia({
    video: true,
    audio: true
}).then(function (stream) {
    streaming.srcObject = stream;
})


first, we have selected the video element of our HTML using the first line of code
then we will ask form the navigator to get the user MediaDevice using this function
for this example, we will use the webcam and the microphone of the user

 navigator.mediaDevices.getUserMedia({
    video: true,
    audio: true
})

and after that, we will use the then method to return a promise and we will get the stream witch to represent the output of our webcam and we will add the source to our video object.

thank you for reading, we hope that you have enjoyed this article, please leave a comment and see you in the next tutorial
How To Access WebCam in JavaScript How To Access WebCam in JavaScript Reviewed by Medics on March 02, 2020 Rating: 5

No comments:

-->
Powered by Blogger.