JSFiddle - React, Tailwind, and code Playground
HTML
<div id='text'>
<p>You must grant access to the Camera first.</p>
<p>Prompt would be shown above this lines, next to the address bar.</p>
<button type='button' id='button'>Take photo</button>
</div>
<video id='video' width="640" height="480"></video>
<canvas id='canvas' style="display:none;"></canvas>
CSS
video {
background: rgba(255,255,255,0.5);
border: 1px solid #ccc;
}
JavaScript
(function(window) {
var nav = window.navigator,
doc = window.document,
//some browsers behave differently
is_webkit = nav.webkitGetUserMedia,
is_mozilla = nav.mozGetUserMedia,
showSnapshot = true,
showVideo = true,
OUTPUT_RATIO = 0.5, //the output is X times the captured image (ex: we upload small photos)
source,
video,
canvas,
button,
ctx,
localMediaStream;
var
initCamera = function() {
video = document.getElementById('video'),
canvas = document.getElementById('canvas'),
button = document.getElementById('button'),
ctx = canvas.getContext('2d');
//make canvas and video the same dimensions
canvas.width = video.width * OUTPUT_RATIO | 0;
canvas.height = video.height * OUTPUT_RATIO | 0;
//turn canvas to visible
canvas.style.display = showSnapshot ? '' : 'none';
video.style.display = showVideo ? '' : 'none';
(button || video).addEventListener('click', takeSnapshot, false); //addEventListener: IE9+ Opera7+ Safari, FFox, Chrome
// if (is_webkit){
// nav.getUserMedia('video', onSuccess, onError);
// }else{
nav.getUserMedia({
video: true
}, onSuccess, onError);
// }
},
onError = function(e) {
alert('Camera permission rejected!', e);
},
onSuccess = function(stream) {
if (is_mozilla) {
source = window.URL.createObjectURL(stream);
} else if (is_webkit) {
source = window.webkitURL.createObjectURL(stream);
} else {
source = stream;
}
...