EN
JavaScript - capture image from device camera using input HTML element (mobile devices only)
10
points
In this short article, we would like to show how capture image from mobile device camera using input HTML element and JavaScript.
Mobile web browsers introduced capture
attribute in <input type="file" accept="image/*" />
HTML element that can be used to handle image 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:
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
input.input {
display: none;
}
span.button {
color: #007bff;
cursor: pointer;
}
span.button:hover {
color: #0056b3;
}
</style>
</head>
<body>
<label class="field">
<input id="input" class="input" type="file" accept="image/*" capture="environment" />
<span id="button" class="button">Capture image</span>
</label>
<script>
var input = document.querySelector('#input');
if ('capture' in input) {
input.addEventListener('change', function(e) {
var files = input.files;
if (files.length === 1) {
var file = files[0];
// using XHR/fetch API we are able to send to backend file as blob
// using FileReader class we are able to read file as base 64
console.log('Image type: ' + file.type);
console.log('Image size: ' + file.size + ' bytes');
} else {
console.log('Image not captured!');
}
});
} else {
var button = document.querySelector('#button');
button.addEventListener('click', function(e) {
e.preventDefault();
console.error('Input capture mode is not supported! Try to use mobile device or other web browser.');
});
}
</script>
</body>
</html>