使用带有javascript的网络摄像头

Using webcam with javascript

本文关键字:网络 摄像头 javascript      更新时间:2024-05-17

我成功地使用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>

试试这个:

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);
    })
})();