let canvas = document.querySelector('canvas');
let capture = document.getElementById('capture');
let start_recording = document.getElementById('start_recording');
let stop_recording = document.getElementById('stop_recording');
let camera_turn = document.getElementById('turn');
let video = document.querySelector('video');
let constraints = {
video: { facingMode: 'user' },
audio: true
};
let recordRTC;
let turn = 'user';
function cameraDisplay(constraints) {
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
video.srcObject = stream;
video.play();
recordRTC = RecordRTC(stream, { type: video });
})
.catch(err => {
console.log('Camera Not Supported');
});
}
camera_turn.addEventListener('click', () => {
if (turn === 'user') {
constraints.video.facingMode = 'environment';
turn = 'environment';
camera_turn.textContent = 'Back';
} else {
constraints.video.facingMode = 'user';
turn = 'user';
camera_turn.textContent = 'Front';
}
cameraDisplay(constraints);
});
window.onload = () => {
cameraDisplay(constraints);
};
let timer = document.createElement('p');
let interval;
start_recording.addEventListener('click', () => {
let timer = document.createElement('p');
timer.textContent = '00:00:00';
document.body.appendChild(timer);
let hour = 0;
let minute = 0;
let second = 0;
let zeros = [0, 0, 0];
interval = setInterval(() => {
if (second > 8) {
zeros[2] = '';
} else {
zeros[2] = 0;
}
if (minute > 8) {
zeros[1] = '';
} else {
zeros[1] = 0;
}
if (hour > 8) {
zeros[0] = '';
} else {
zeros[0] = 0;
}
timer.textContent = `${zeros[0]}${hour}:${zeros[1]}${minute}:${zeros[2]}${++second}`;
if (second == 59) {
second = 0;
minute++;
} else if (minute == 59) {
hour++;
minute = 0;
} else if (hour == 23) {
hour = 0;
second = 0;
minute = 0;
}
}, 200);
});
stop_recording.addEventListener('click', () => {
clearInterval(interval);
document.body.removeChild(timer);
recordRTC.stopRecording(() => {
let blob = recordRTC.getBlob();
let url = URL.createObjectURL(blob);
let anchor = document.createElement('a');
anchor.href = url;
anchor.download = 'captured_video.mp4';
anchor.click();
URL.revokeObjectURL(url);
document.body.appendChild(anchor);
});
});
capture.addEventListener('click', () => {
let context = canvas.getContext('2d');
context.drawImage(video, 0, 0, video.videoWidth, video.videoWidth);
});
</script>