-
-
Save bpdarlyn/43e0a0785d1fe9940de11e52945493ce to your computer and use it in GitHub Desktop.
WebCam component in React. Works on Android, iOS and Desktop (With camera installed)
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
import React, {Component} from 'react'; | |
const constraints = {video: {facingMode: "user"}, audio: false}; | |
import {b64toBlob} from './../../main-app/helpers/functions'; | |
import axios from 'axios'; | |
navigator.getMedia = ( navigator.getUserMedia || | |
navigator.webkitGetUserMedia || | |
navigator.mozGetUserMedia); | |
import PropTypes from 'prop-types'; | |
export default class TakePicture extends Component { | |
state = { | |
showCamera: false, // flag to show and hidden the component camera | |
cameraOutput: null, // node to show the capture than has been taken | |
} | |
componentDidMount() { | |
this.listenCameraClick(); | |
} | |
listenCameraClick(){ | |
$('body').on('click', '.open-camera', ({currentTarget}) => { | |
this.cameraStart($(currentTarget).siblings('img')); | |
}); | |
} | |
cameraStart(jqueryImage) { | |
navigator.mediaDevices | |
.getUserMedia(constraints) | |
.then( (stream) => { | |
this.setState({showCamera: true, cameraOutput: jqueryImage}); | |
this.cameraView.srcObject = stream; | |
}) | |
.catch(function (error) { | |
switch (error.name) { | |
case 'NotAllowedError': | |
alert('The permission was denied, please enabled your camera or reload!'); | |
break; | |
} | |
console.error("Oops. Something is broken.", error); | |
}); | |
} | |
_handleCamera = () => { | |
this.cameraSensor.width = this.cameraView.videoWidth; | |
this.cameraSensor.height = this.cameraView.videoHeight; | |
this.cameraSensor.getContext("2d").drawImage(this.cameraView, 0, 0); | |
this.state.cameraOutput.attr('src',this.cameraSensor.toDataURL("image/jpeg", 1)); | |
this.save(this.state.cameraOutput.attr('src')); | |
this.setState({showCamera: false}); | |
}; | |
save(b64ImageUrl){ | |
let inputField = this.state.cameraOutput.parent().siblings('.attachment-field'); | |
inputField.val(b64ImageUrl); | |
} | |
render() { | |
return this.state.showCamera && <main className={'camera-container'}> | |
<video ref={(cv) => this.cameraView = cv } className={'camera--view'} autoPlay={true} playsInline={true} /> | |
<img className={'camera--output'} ref={(co) => this.cameraOutput = co } src="//:0" alt=""/> | |
<button onClick={this._handleCamera} className={'camera--trigger'}> | |
<i className={'fas fa-camera'}></i> | |
</button> | |
<canvas className={'camera--sensor'} ref={(cs) => this.cameraSensor = cs}/> | |
</main>; | |
} | |
} | |
TakePicture.propTypes = { | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment