Uploading a picture taken from a webcam

2019-08-03 02:06发布

How do i upload a picture that i took from a webcam, i've found a code that worked (only on Chrome)

i've used the code, and when clic on Take picture, i got the picture but i dont see it on the source?

<video autoplay id="vid" style="display:none;"></video>
<canvas id="canvas" width="640" height="480" style="border:1px solid #d3d3d3;"></canvas><br>
<button onclick="snapshot()">Take Picture</button>

<script type="text/javascript">

var video = document.querySelector("#vid");
var canvas = document.querySelector('#canvas');
var ctx = canvas.getContext('2d');
var localMediaStream = null;

var onCameraFail = function (e) {
    console.log('Camera did not work.', e);
};

function snapshot() {
    if (localMediaStream) {
        ctx.drawImage(video, 0, 0);
    }
}

navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia({video:true}, function (stream) {
    video.src = window.URL.createObjectURL(stream);
    localMediaStream = stream;
}, onCameraFail);

</script>

How do i add it to a form that have a picture element

<input name="avatar" class="avatar" type="file" required>

as you can see, the field is required, so if it is added to that field the form will see it as a non-empty?

Why it dont work on Opera? i use Opera 12.15

Update: i found how to convert to canvas to image, but dont know how to fill it in the image:

a = canvas.toDataURL("image/jpeg")
document.getElementById("avatar").src = a

if i use the javascript console, i get the source, but if i validate the form, the form thinks that the image is still missing and it is blank.

any ideas?

1条回答
可以哭但决不认输i
2楼-- · 2019-08-03 02:45

Build the SetInterval with snapshot() runing in 300ms.

The button only stop the interval, ;)


<button onclick="clearInterval(ivl)">Take Picture</button>

var ivl = setInterval(function(){  snapshot(); },300);
查看更多
登录 后发表回答