使用getUserMedia访问设备摄像头

时间:2016-10-28 07:41:44

标签: javascript html5 getusermedia

下面的代码成功运行,直到我添加了一些额外的代码,因为我试图让用户知道他们的相机准备好/可用或不可用。我的HTML看起来像:

<div id="notes">
</div>
<div id="video-container">
<video id="camera-stream" width="500" autoplay></video>
</div>

这里是.js

<script type="text/javascript">
    window.onload = function() {
    var statusHTML = '<ul>';
  navigator.getUserMedia = (navigator.getUserMedia ||
                            navigator.webkitGetUserMedia ||
                            navigator.mozGetUserMedia || 
                            navigator.msGetUserMedia);
if (navigator.getUserMedia) {
  navigator.getUserMedia(
    {
      video: true,
      audio: true
    },
    function(localMediaStream) {
statusHTML += '<li>You have a camera!</li>';
var vid = document.getElementById('camera-stream');
vid.src = window.URL.createObjectURL(localMediaStream);
    },
    function(err) {
  statusHTML += '<li>You dont have a camera!</li>';
      console.log('The following error occurred when trying to use getUserMedia: ' + err);
    }
  );
  statusHTML += '</ul>';
  document.getElementById('notes').innerHTML = statusHTML;
} else {
  alert('Sorry, your browser does not support getUserMedia');
}
}
</script>

我添加了这4个不起作用的代码,我不确定我是否做得对:

  var statusHTML = '<ul>';
  statusHTML += '<li>You have a camera!</li>';
  statusHTML += '<li>You dont have a camera!</li>';
  statusHTML += '</ul>';
  document.getElementById('notes').innerHTML = statusHTML;

总而言之,我正在尝试向用户加载页面的页面打印消息应该说他们有可用的相机。任何帮助将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

尝试直接更改innerHTML,而不是在带有变量的函数之后。我尝试过它并且工作正常:

window.onload = function() {
    navigator.getUserMedia = (navigator.getUserMedia ||
                            navigator.webkitGetUserMedia ||
                            navigator.mozGetUserMedia || 
                            navigator.msGetUserMedia);
    if (navigator.getUserMedia) {
        navigator.getUserMedia(
        {
          video: true,
          audio: true
        },
        function(localMediaStream) {
          document.getElementById('notes').innerHTML = '<ul><li>You have a camera!</li></ul>';
          var vid = document.getElementById('camera-stream');
          vid.src = window.URL.createObjectURL(localMediaStream);
        },
        function(err) {
          document.getElementById('notes').innerHTML = '<ul><li>You dont have a camera!</li></ul>';
          alert('The following error occurred when trying to use getUserMedia: ' + err);
        }
        );
    } else {
      alert('Sorry, your browser does not support getUserMedia');
    }
}