Skip to content

Instantly share code, notes, and snippets.

@bpdarlyn
Created May 11, 2020 19:36
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 bpdarlyn/43e0a0785d1fe9940de11e52945493ce to your computer and use it in GitHub Desktop.
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)
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