JSFiddle - React, Tailwind, and code Playground
by ethanpil
HTML
<video id="camera" autoplay></video>
<button id="capture">Capture Image</button>
<div class="crop-container">
<img id="displayed-photo" src="" alt="Captured Photo">
<div class="crop-box"></div>
</div>
CSS
/* Add some basic styling */
body { font-family: Arial, sans-serif; }
#camera { width: 100%; max-width: 640px; }
.crop-container { position: relative; overflow: hidden; }
.crop-box {
JavaScript
const camera = document.getElementById('camera');
const captureButton = document.getElementById('capture');
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// Request access to the user's camera
navigator.mediaDevices.getUserMedia({ video: true })
.then(function(stream) {
// Get the video element by its ID
var video = document.getElementById('camera');
// Play the video stream in the video element
video.srcObject = stream;
})
.catch(function(err) {
console.log("An error occurred: " + err);
});
} else {
console.log("Your browser does not support accessing media devices.");
}
captureButton.addEventListener('click', async () => {
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
const photo = await new Promise(resolve =>
stream.getVideoTracks()[0].requestFrame(resolve)
);
const img = document.getElementById('displayed-photo');
img.src = URL.createObjectURL(photo);
});
let cropper;
function initCropper() {
cropper = new Cropper(document.getElementById('displayed-photo'), {
autoCropArea: 1,
movable: false,
scalable: false,
zoomable: false,
ready: function(instance) {
instance.on('crop', function(event) {
// Handle the cropped area
console.log(event.detail.x, event.detail.y, event.detail.width, event.detail.height);
});
}
});
}
// Call initCropper after the photo is displayed
document.getElementById('displayed-photo').addEventListener('load', initCropper);
function ready(fn) {
if (document.readyState !== 'loading') {
fn();
return;
}
document.addEventListener('DOMContentLoaded', fn);
}
ready(function(){
})