从浏览器中访问摄像头

55

能否通过浏览器访问(苹果设备上)内置的相机?

最优解决方案是使用客户端javascript。希望避免使用Java或Flash。


15
禁用自己的相机。 - Aesthete
请参见:https://dev59.com/ymw05IYBdhLWcg3w3lkl#6976093 - Ayush
2
@Aesthete:非常像 HTML5 的 geolocation 对象,它会先请求权限。 - Ayush
据我所记,Flash可以访问网络摄像头/相机。但是我对JS有疑问。 - nhahtdh
10个回答

19
截至2017年,WebKit宣布在Safari上支持WebRTC
现在您可以使用 video 和标准的Javascript WebRTC 访问它们。
例如:
var video = document.createElement('video');
video.setAttribute('playsinline', '');
video.setAttribute('autoplay', '');
video.setAttribute('muted', '');
video.style.width = '200px';
video.style.height = '200px';

/* Setting up the constraint */
var facingMode = "user"; // Can be 'user' or 'environment' to access back or front camera (NEAT!)
var constraints = {
  audio: false,
  video: {
   facingMode: facingMode
  }
};

/* Stream it to video element */
navigator.mediaDevices.getUserMedia(constraints).then(function success(stream) {
  video.srcObject = stream;
});

玩一玩吧。


你好,但是iOS的Webview还不支持吗?你有没有什么解决方法可以在iOS的Webview中访问相机? 其他问题参考:https://dev59.com/h7Hma4cB1Zd3GeqPJk89 谢谢。 - Alvin Theodora

17

6

1
这在iOS 10设备上无法工作(未测试其他设备)。它会显示“此浏览器不支持getUserMedia”或类似的内容。 - jdmdevdotnet

5

是的,可以从浏览器访问相机。以下是对我有效的代码:

<html><head>
</head><body>
    <video src="" ></video>
    <br />
<button id='flipCamera'>Flip</button>
</body>
<script>
  var front = false;
var video = document.querySelector('video');
  document.getElementById('flipCamera').onclick = function() { front = !front; };
  var constraints = { video: { facingMode: (front? "user" : "environment"), width: 640, height: 480  } };
  navigator.mediaDevices.getUserMedia(constraints)
  .then(function(mediaStream) {
    video.srcObject = mediaStream;
    video.onloadedmetadata = function(e) {
    video.play();
};
})
.catch(function(err) { console.log(err.name + ": " + err.message); })
</script></html>


2
你可以使用HTML5来实现这个目标:
<video autoplay></video>
<script>
  var onFailSoHard = function(e) {
    console.log('Reeeejected!', e);
  };

  // Not showing vendor prefixes.
  navigator.getUserMedia({video: true, audio: true}, function(localMediaStream) {
    var video = document.querySelector('video');
    video.src = window.URL.createObjectURL(localMediaStream);

    // Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
    // See crbug.com/110938.
    video.onloadedmetadata = function(e) {
      // Ready to go. Do some stuff.
    };
  }, onFailSoHard);
</script>

Source


2
    <style type="text/css">
        #container {
            margin: 0px auto;
            width: 500px;
            height: 375px;
            border: 10px #333 solid;
        }

        #videoElement {
          width: 500px;
          height: 375px;
          background-color: #777;
        }
    </style>    
<div id="container">
            <video autoplay="true" id="videoElement"></video>
        </div>
        <script type="text/javascript">
          var video = document.querySelector("#videoElement");
          navigator.getUserMedia = navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia;
    
          if(navigator.getUserMedia) {
            navigator.getUserMedia({video:true}, handleVideo, videoError);
          }
    
          function handleVideo(stream) {
            video.srcObject=stream;
            video.play();
          }
    
          function videoError(e) {
    
          }
        </script>

请提供更多的解释! - Afsanefda
1
navigator.getUserMedia()已经被弃用,请使用更新的版本navigator.mediaDevices.getUserMedia() - Splines

0
由于navigator.getUserMedia已被弃用并成为遗留API的一部分,建议使用navigator.mediaDevices.getUserMedia代替。它已被证明与Firefox和Chrome兼容。
function loadCamera ()
{
   let v = document.getElementById ("myvideo");
   navigator.mediaDevices.getUserMedia({video:{width:v.width, height:v.height}})
      .then((mediaStream) => {  v.srcObject = mediaStream; })
      .catch(e => { console.error(`${e.name}: ${e.message}`); });

   v.play();
}

loadCamera ();

另一个选择是将其加载到内存中,如果视频图像打算在显示之前进行操作或处理,例如背景替换或作为WebGL2纹理。
function makeVideo (height, width)
{
   let video  = document.createElement ("video");
   video.height      = height;
   video.width       = width;
   video.autoplay    = true;
   video.playsInline = true;
   video.muted       = true;
   video.loop        = true;
   return video;
}
async function loadCamera (height, width)
{
   let v  = makeVideo (height, width);

   navigator.mediaDevices.getUserMedia({video:{width:width, height:height}})
      .then((mediaStream) => {  v.srcObject = mediaStream; })
      .catch(e => { console.error(`${e.name}: ${e.message}`); });

   v.play();
   return v;

}

then处理程序中添加任何处理
loadCamera (180, 320).then(video => { document.body.appendChild(video); });

0

链接似乎不再指向教程。 - Stretch0

0

**SIMPLE JAVASCRIPT VANILLA **

var video = document.querySelector("#videoElement");

if (navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({ video: true })
        .then(function (stream) {
            video.srcObject = stream;
        })
        .catch(function (err0r) {
            console.log("Something went wrong!");
        });
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content="stuff, to, help, search, engines, not" name="keywords">
<meta content="What this page is about." name="description">
<meta content="Display Webcam Stream" name="title">
<title>Display Webcam Stream</title>
<style>
  #container{
   align-self: center;
   margin-left: 350px;
   align-items: center;
   justify-content: center;
position: relative;
    width: 1000px;
    height: 1000px;
       background-color: black;
       padding: 3px;
  }
  #videoElement{
    transform: rotate(90deg);
   align-self: center;
   height: 50a0px;
   left: 20;
   width: 700px;
   position:absolute;
   padding: 1px;
   top: 120px;
  }
</style>
</head>
  
<body>
<div id="container">
    <video autoplay="true" id="videoElement">
    </video>
</div>
<script src="index.js">

</script>
</body>
</html>


在Safari和Chrome上只是一个黑色背景。它要求使用相机的权限,但没有任何内容出现。 - Ollie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接