使用网络摄像头与JavaScript

时间:2015-02-26 03:35:40

标签: javascript

我成功使用Firefox访问我的网络摄像头。但是我的代码不适用于chrome或Internet Explorer。我在这做错了什么?

<html>
<head>
<script>
function loading(){ navigator.getUserMedia = ( navigator.getUserMedia ||  navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);


   if (navigator.getUserMedia)
   {
     var thevid = {video: true, audio: false};
     navigator.getUserMedia(thevid, function (localmediastream)
   {
     var video = document.querySelector('#forVid');
      video.src = window.URL.createObjectURL(localmediastream);
   }, function(err){
    alert(err);})
   }

 }

</script>
</head>
<body onload = "loading()">

<video id = "forVid" style="position:absolute; top:0; left:0;" autoplay="true" height="600" width="600">

</body>
</html>

1 个答案:

答案 0 :(得分:1)

试试这个:

http://jsfiddle.net/wr65rx4s/

<强> HTML

<video id="forVid" style="position:absolute; top:0; left:0;" autoplay="true" height="600" width="600">

<强>的JavaScript

(function () {
    navigator.getMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia);

    navigator.getMedia(
    // constraints
    {
        video: true,
        audio: false
    },

    // success callback
    function (mediaStream) {
        var video = document.getElementsByTagName('video')[0];
        video.src = window.URL.createObjectURL(mediaStream);
        video.play();
    },
    //handle error
    function (error) {
        console.log(error);
    })
})();