Skip to content

Instantly share code, notes, and snippets.

@hwclass
Created September 14, 2017 14:30
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 hwclass/7fd4cdeec3e792ba077093aa20fee694 to your computer and use it in GitHub Desktop.
Save hwclass/7fd4cdeec3e792ba077093aa20fee694 to your computer and use it in GitHub Desktop.
Activate camera gist
/**
* Retrieves the devices matching the kind property with the inputKind argument
* @param {String} inputKind The type of the input like 'videoinput'
* @param {MediaDeviceInfo} device The device instance
* @return {MediaDeviceInfo} The matching media device
*/
const getDeviceWith = ({ inputKind, device }) => {
return (device.kind === inputKind) && device
}
/**
* Returns the video tracks of tha current stream within that specified index
* @param {[type]} stream The stream
* @param {[type]} idx Video track stream index
* @return {[type]} [description]
*/
const getVideoTracksOfStream = (stream, idx) => (stream && stream.getVideoTracks()[idx])
/**
* Generates the media object with concrete properties like device id and width for canvas
* @param {MediaDeviceInfo} device The device information
* @return {MediaStream} The structured MediaStream object
*/
const buildUserMedia = (device) => {
return navigator.mediaDevices.getUserMedia({
video: {
deviceId: { exact : device.deviceId },
width: { max: 640 }
}
})
}
/**
* Binds the camera device within the element specified as the argument
* @param {HTMLElement} el The element to initialize camera canvas
* @return N/A
*/
const startVideoCapturing = (el) => {
navigator.mediaDevices.enumerateDevices()
.then((devices) => {
let devicesWithInputKind = devices.filter(device => getDeviceWith({ inputKind: 'videoinput', device }))
return Promise.resolve(buildUserMedia(devicesWithInputKind[0]))
}).then((stream) => {
self.setState({
videoSrc: window.URL.createObjectURL(stream),
capturer: new ImageCapture(getVideoTracksOfStream(stream, 0))
})
return Promise.resolve(this.state.videoSrc === '')
}).then((status) => el.disabled = status /* add state.isButtonEnabled = false */)
}
/**
* Activates the physical camera on the web page
* @param {[type]} e Event for the element clicked
* @return N/A
*/
const activateCamera = (e) => startVideoCapturing(e.target)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment