Skip to content

Instantly share code, notes, and snippets.

@zachberry
Last active August 14, 2018 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachberry/c4a54ff5b5edd40abfed6b3e283fa01f to your computer and use it in GitHub Desktop.
Save zachberry/c4a54ff5b5edd40abfed6b3e283fa01f to your computer and use it in GitHub Desktop.
Webcam in the browser example - https://codepen.io/zachberry/pen/gjyajp
// 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