Last active
August 14, 2018 00:16
-
-
Save zachberry/c4a54ff5b5edd40abfed6b3e283fa01f to your computer and use it in GitHub Desktop.
Webcam in the browser example - https://codepen.io/zachberry/pen/gjyajp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copy this code and paste it in a dev tools console - Must be on an HTTPS site (or localhost) | |
document.write("<video></video>"); | |
navigator.getUserMedia( | |
{ video: true }, // Ask for video | |
onGetUserMediaSuccess, | |
onError | |
); | |
function onError(e) { console.error(e) } | |
function onGetUserMediaSuccess() { | |
navigator.mediaDevices.enumerateDevices().then(devices => { | |
devices.forEach(device => { | |
if (device.kind === "videoinput") { | |
console.log(device); // InputDeviceInfo { deviceId, label, ...} | |
getStream(device.deviceId); | |
} | |
}); | |
}); | |
} | |
function getStream(id) { | |
if (!id) return; | |
let constraints = { deviceId: { exact: id } }; | |
navigator.getUserMedia( | |
{ video: constraints }, | |
onGetDeviceSuccess, | |
onError | |
); | |
} | |
function onGetDeviceSuccess(stream) { | |
console.log(stream); //MediaStream | |
let videoEl = document.getElementsByTagName('video')[0] | |
videoEl.srcObject = stream; | |
videoEl.play(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment