Lasse
Lasse

Reputation: 1163

HTML media capture one click

With media capture we can capture an image through browser on iOS/Android. You will get the popup to select file or new image. And if user captures a new image then after capture, the user has to click "Use image".

But is it some how possible to capture the image straight away after user clicks a button? The scenario is to always capture an image of the user when the user logs in to the service.

It must be able to run on a mobile device either Android or iOS.

Upvotes: 2

Views: 373

Answers (1)

Joel
Joel

Reputation: 15752

If you want to use media capture, all you can do is wrapping the input field into a label (or reference it with for=id) and style the label as a button:

<label style="border: 1px solid black;">
    This is my custom capture button.
    <input style="display: none;" type="file" accept="image/*;capture=camera">
</label>

The other option is taking advantage of WebRTC:

<script>
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
navigator.getUserMedia({video: true}, function (stream) {
    var video = document.querySelector('video'); 
    video.src = window.URL.createObjectURL(stream);
    video.onplay = function () {
        var canvas = document.querySelector('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        var ctx = canvas.getContext('2d'); 
        ctx.drawImage(video, 0, 0);
        stream.stop();
        var image = canvas.toDataURL('image/jpeg');
    };

    }, function (err) {
        alert('Error: ' + err);
    }
);
</script>

<video autoplay style="display:none;"></video> 
<canvas></canvas>

This code uses getUserMedia to access the camera and shows it in a video element. When the video starts playing (you can of course also use a different event), it draws a frame on a canvas and converts the canvas to a JPEG image (Data URL). This image can then for example be transferred to a server. The disadvantage of this approach is that it doesn't work on iOS and only on newer Android devices. I have only tested it in Chrome.

Upvotes: 3

Related Questions