Reputation: 63
I found some code online to access my webcam. It accesses the webcam but it doesn't display what it see's. I know this is normal because there is no html in the document but I was wondering how I could display the result. The code I found is:
var constraints = { audio: true, video: { width: 1280, height: 720 } };
navigator.mediaDevices.getUserMedia(constraints)
.then(function(mediaStream) {
var video = document.querySelector('video');
video.srcObject = mediaStream;
video.onloadedmetadata = function(e) {
video.play();
};
})
.catch(function(err) { console.log(err.name + ": " + err.message); });
I thank you for your help.
Upvotes: 0
Views: 1025
Reputation: 1636
You're probably missing a video
tag in your HTML, used to "dump" the webcam's stream. Since it's not a good idea to reference the tag by its tag name (video
), you should use an ID instead (for example, #webcam
). Just create a video tag with that id:
<video id="webcam"></video>
Update your code, within document.querySelector
, to reference your new tag:
var constraints = { audio: true, video: { width: 1280, height: 720 } };
navigator.mediaDevices.getUserMedia(constraints)
.then(function(mediaStream) {
var video = document.querySelector('#webcam'); // <- Here
video.srcObject = mediaStream;
video.onloadedmetadata = function(e) {
video.play();
};
})
.catch(function(err) { console.log(err.name + ": " + err.message); });
Here's a working example on JSFiddle.
Also, remember to allow the web browser to use your webcam and microphone.
Upvotes: 2