react-webcamera
Version:
React webcamera component with direct access to the camera data
139 lines (114 loc) • 3.56 kB
JavaScript
import React, { Component } from 'react';
import PropTypes from 'prop-types';
CameraComponent.defaultProps = {
demo: false
}
CameraComponent.propTypes = {
demo: PropTypes.bool,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
filter: PropTypes.func
}
export default class CameraComponent extends Component {
constructor(props){
super(props);
this.navigator = navigator;
this.pause = true;
this.draw = this.draw.bind(this);
this.drawToIntermediateCanvas = this.drawToIntermediateCanvas.bind(this);
this.drawToFinalCanvas = this.drawToFinalCanvas.bind(this);
}
setupGetMedia(){
this.navigator.getMedia = (
this.navigator.getUserMedia ||
this.navigator.webkitGetUserMedia ||
this.navigator.mozGetUserMedia ||
this.navigator.msGetUserMedia
)
}
startVideo(video){
// Show error message if camera is not supported by the browser
if(!this.navigator.getMedia){
displayErrorMessage("Your browser doesn't have support for the navigator.getUserMedia interface.");
}
else{
// Request the camera.
this.navigator.getMedia(
{
video: true
},
// Success Callback
function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
video.onplay = function() {
//showVideo();
};
},
// Error Callback
function(err) {
console.error("There was an error with accessing the camera stream: " + err.name, err);
}
);
}
}
setupCanvas(){
this.canvas = this.refs.finalCanvas;
this.context = this.canvas.getContext('2d');
this.intermediateCanvas = this.refs.intermediateCanvas;
this.intermediateContext = this.intermediateCanvas.getContext('2d');
}
drawToIntermediateCanvas(){
this.intermediateContext.drawImage(this.refs.cameraStream, 0, 0, this.props.width, this.props.height);
}
drawToFinalCanvas(data){
this.context.putImageData(data, 0, 0);
}
draw(){
this.drawToIntermediateCanvas();
//Apply filters/functions on the extracted video data
let idata = this.getVideoData();
let data = idata.data;
let filteredData;
let filteredImageData = idata;
if(this.props.filter){
filteredData = this.props.filter(data);
filteredImageData = new ImageData(filteredData, this.props.width, this.props.height);
}
this.drawToFinalCanvas(filteredImageData);
setTimeout(this.draw,80);
}
getVideoData(){
let idata = this.intermediateContext.getImageData(0,0,this.props.width,this.props.height);
return idata;
}
componentDidMount(){
let video = this.refs.cameraStream
this.setupGetMedia();
this.startVideo(video);
this.setupCanvas();
}
render(){
return(
<div className="camera">
<video width={+this.props.width}
height={+this.props.height}
muted
hidden
ref="cameraStream"
controls
onPlay={this.draw}>
</video>
<canvas width={+this.props.width}
height={+this.props.height}
hidden={!this.props.demo}
ref="intermediateCanvas">
</canvas>
<canvas width={+this.props.width}
height={+this.props.height}
ref="finalCanvas">
</canvas>
</div>
);
}
}