Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Some things that can go wrong when setting up a camera with getUserMedia.
function cameraReady(videoElement) {
console.log('cameraReady: checking...');
if (videoElement) {
if (videoElement.srcObject) {
let tracks = videoElement.srcObject.getVideoTracks();
if (tracks.length > 0) {
if (tracks[0].readyState == 'live') {
let w = videoElement.videoWidth, h = videoElement.videoHeight;
if (w > 0 || h > 0) {
console.log('cameraReady: live! ' + w + 'x' + h);
return true;
}
console.error('cameraReady: live, but 0x0');
return false;
}
console.error('cameraReady: readyState is ' + tracks[0].readyState);
return false;
}
console.error('cameraReady: no tracks');
return false;
}
console.error('cameraReady: no srcObject');
return false;
}
console.error('cameraReady: no element');
return false;
}
function initCamera(videoElement) {
// these are essential on iOS
videoElement.setAttributeNode(document.createAttribute('autoplay'));
videoElement.setAttributeNode(document.createAttribute('playsinline'));
// don't re-initialize the camera if it's already live
if (cameraReady(videoElement)) {
console.log('initCamera: done!');
return Promise.resolve();
}
return navigator.mediaDevices
.getUserMedia({
audio: false,
video: { facingMode: 'user' }
})
// stream is ready, set to the video element
// don't return until the metadata is ready
// https://stackoverflow.com/a/41866914/940196
.then(stream => new Promise(resolve => {
console.log('initCamera: setting srcObject...');
videoElement.onloadedmetadata = resolve;
videoElement.srcObject = stream;
}))
.then(() => console.log('initCamera: done!'))
.catch(err => {
console.error(err);
alert(config.cameraErrorMessage);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment