Languages
[Edit]
EN

JavaScript - capture video from device camera using input HTML element (mobile devices only)

6 points
Created by:
Welsh
772

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:

// 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="video/*" capture="environment" />
    <span id="button" class="button">Capture video</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('Video type: ' + file.type);
                console.log('Video size: ' + file.size + ' bytes');
            } else {
                console.log('Video not captured!');
            }
        });
    } else {
        var button = document.querySelector('#button');
        button.addEventListener('click', function(e) {
            e.preventDefault();
            console.error('Video capture mode is not supported! Try to use mobile device or other web browser.');
        });
    }

  </script>
</body>
</html>

 

See also

  1. JavaScript - capture image from device camera using input HTML element (mobile devices only)

References

  1. HTML attribute: capture - MDN Docs

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join