Skip to content

Instantly share code, notes, and snippets.

@philnash
Created March 15, 2018 02:38
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 philnash/b79c6f775b194cbbb91fcb9b1b2cf791 to your computer and use it in GitHub Desktop.
Save philnash/b79c6f775b194cbbb91fcb9b1b2cf791 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Camera selection</title>
<style>
html,
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<video id="video" autoplay playsinline style="width: 100vw; max-width: 600px;"></video>
<button id="button">Get camera</button>
<select id="select">
<option></option>
</select>
<textarea id="textarea" style="height: 80vh; width: 100vw;"></textarea>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script>
const video = document.getElementById('video');
const button = document.getElementById('button');
const select = document.getElementById('select');
let currentStream;
function stopMediaTracks(stream) {
stream.getTracks().forEach((track) => {
track.stop();
})
}
function log(string) {
textarea.innerHTML += string + "\n";
console.log(string);
}
function gotDevices(mediaDevices) {
select.innerHTML = '';
select.appendChild(document.createElement('option'));
let count = 1;
mediaDevices.forEach((mediaDevice) => {
if (mediaDevice.kind === 'videoinput') {
log(mediaDevice.deviceId);
log(mediaDevice.label);
const option = document.createElement('option');
option.value = mediaDevice.deviceId;
const label = mediaDevice.label || `Camera ${count++}`;
const textNode = document.createTextNode(label);
option.appendChild(textNode);
select.appendChild(option);
}
})
}
button.addEventListener('click', (event) => {
if (typeof currentStream !== 'undefined') { stopMediaTracks(currentStream); }
const videoConstraints = {};
if (select.value === '') {
videoConstraints.facingMode = 'environment';
} else {
videoConstraints.deviceId = { exact: select.value };
}
const constraints = {
video: videoConstraints,
audio: false
}
navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
currentStream = stream;
video.srcObject = stream;
return navigator.mediaDevices.enumerateDevices();
}).then(gotDevices).catch((error) => { log(error); });
})
navigator.mediaDevices.enumerateDevices().then(gotDevices);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment