使用带有Javascript的网络摄像头拍摄快照

时间:2016-10-05 12:54:24

标签: javascript

制作页面以使用网络摄像头拍摄快照。但突然间它停止了在每台电脑上工作。我是否打错了,我看不到自己,或者有人有想法也解决这个问题吗?

  • 添加了比特以及

    // Put event listeners into place
    window.addEventListener("DOMContentLoaded", function() {
        // Grab elements, create settings, etc.
        var canvas = document.getElementById("canvas"),
            context = canvas.getContext("2d"),
            video = document.getElementById("video"),
            videoObj = { "video": true },
            image_format= "jpeg",
            jpeg_quality= 85,
            errBack = function(error) {
                console.log("Video capture error: ", error.code); 
            };
    
    
        // Put video listeners into place
        if(navigator.getUserMedia) { // Standard
            navigator.getUserMedia(videoObj, function(stream) {
                video.src = stream;
                video.play();
                $("#snap").show();
            }, errBack);
        } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
            navigator.webkitGetUserMedia(videoObj, function(stream){
                video.src = window.URL.createObjectURL(stream);
                video.play();
                $("#snap").show();
            }, errBack);
        } else if(navigator.mozGetUserMedia) { // moz-prefixed
            navigator.mozGetUserMedia(videoObj, function(stream){
                video.src = window.URL.createObjectURL(stream);
                video.play();
                $("#snap").show();
            }, errBack);
        }
    
    
    
    // Get-Save Snapshot - image 
        document.getElementById("snap").addEventListener("click", function() {
            context.drawImage(video, 0, 0, 640, 480);
            // the fade only works on firefox?
            $("#video").fadeOut("slow");
            $("#canvas").fadeIn("slow");
            $("#snap").hide();
            $("#reset").show();
            $("#upload").show();
    

1 个答案:

答案 0 :(得分:2)

在此部分代码中,您永远不会将视频绘制到画布上。

此外,navigator.getUserMedia不再是“标准”,它已更新为navigator.mediaDevices.getUserMedia,它将返回Promise。

var ctx = c.getContext('2d');
var vid = document.createElement('video');

vid.oncanplay = function() {
  c.width = this.videoWidth;
  c.height = this.videoHeight;
  draw();
}

navigator.mediaDevices.getUserMedia({
  video: true
}).then((stream) => {
  vid.srcObject = stream;
  vid.play();
});

function draw() {
  ctx.drawImage(vid, 0, 0);
  requestAnimationFrame(draw);
}
<canvas id="c"></canvas>

a fiddle for chrome因为它不允许在SO片段中使用gUM。

Ps:如果您需要支持较旧的实施,请查看官方WebRTC polyfill,adapter.js