<!--
        Ideally these elements aren't created until it's confirmed that the 
        client supports video/camera, but for the sake of illustrating the 
        elements involved, they are created with markup (not JavaScript)
-->
<html>

<head>
<title>Snap Uploader</title>
</head>

<body>
<video id="video" width="640" height="480" autoplay></video>
<canvas id="snapshot" width="640" height="480" style="display:none"></canvas>
<br>
<button id="snap">Upload Snapshot</button>

<form id="image_uploader_form" enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" id="image_uploader_field" name="image_uploader_field" value="" />
</form>
</body>

</html>

<script type="text/javascript">
// Grab elements, create settings, etc.
var video = document.getElementById('video');

// Get access to the camera!
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    // Not adding `{ audio: true }` since we only want video now
    navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
        //video.src = window.URL.createObjectURL(stream);
        video.srcObject = stream;
        video.play();
    });
}

// Elements for taking the snapshot
var snapshot = document.getElementById('snapshot');
var context = snapshot.getContext('2d');
var video = document.getElementById('video');

// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
        context.drawImage(video, 0, 0, 640, 480);

    document.getElementById("video").setAttribute("style", "display:none");
    document.getElementById("snapshot").setAttribute("style", "display:inline-block");

    setTimeout(function(){
        uploadSnapshot();
    }, 2000);
});


function uploadSnapshot()
{
    document.getElementById('image_uploader_field').value = snapshot.toDataURL('image/png');
    document.forms["image_uploader_form"].submit();
}
</script>