EN
JavaScript - capture video from device camera using input HTML element (mobile devices only)
7 points
In this short article, we would like to show how capture video from mobile device camera using input HTML element and JavaScript.
Mobile web browsers introduced capture
attribute in <input type="file" accept="video/*" />
HTML element that can be used to handle video directly from mobile device camera. The idea is simple: instead of file selector, web browser runs camera application forwarding result into web browser input
field.
Capture attribute accepts values:
capture="user"
that enables facing camera,capture="environment"
that enables outward camera.
Practical example:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
input.input {
7
display: none;
8
}
9
10
span.button {
11
color: #007bff;
12
cursor: pointer;
13
}
14
15
span.button:hover {
16
color: #0056b3;
17
}
18
19
</style>
20
</head>
21
<body>
22
<label class="field">
23
<input id="input" class="input" type="file" accept="video/*" capture="environment" />
24
<span id="button" class="button">Capture video</span>
25
</label>
26
<script>
27
28
var input = document.querySelector('#input');
29
30
if ('capture' in input) {
31
input.addEventListener('change', function(e) {
32
var files = input.files;
33
if (files.length === 1) {
34
var file = files[0];
35
// using XHR/fetch API we are able to send to backend file as blob
36
// using FileReader class we are able to read file as base 64
37
console.log('Video type: ' + file.type);
38
console.log('Video size: ' + file.size + ' bytes');
39
} else {
40
console.log('Video not captured!');
41
}
42
});
43
} else {
44
var button = document.querySelector('#button');
45
button.addEventListener('click', function(e) {
46
e.preventDefault();
47
console.error('Video capture mode is not supported! Try to use mobile device or other web browser.');
48
});
49
}
50
51
</script>
52
</body>
53
</html>