获取用户媒体api无法在本地主机中工作

时间:2014-10-25 21:07:34

标签: html5 html5-video getusermedia

我正在探索获取用户媒体的API,并尝试在我的localhost中运行api,下面附带示例代码

在jsbin here

中工作正常

但在localhost中完全失败并出现以下错误

未捕获的TypeError:无法读取null capture.html的属性“addEventListener”:43 未捕获的TypeError:无法设置属性'src'为null

代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>

<script>
(function() {

var streaming = false,
  video        = document.querySelector('#video'),
  cover        = document.querySelector('#cover'),
  canvas       = document.querySelector('#canvas'),
  photo        = document.querySelector('#photo'),
  startbutton  = document.querySelector('#startbutton'),
  width = 200,
  height = 0;

  navigator.getMedia = ( navigator.getUserMedia || 
                     navigator.webkitGetUserMedia ||
                     navigator.mozGetUserMedia ||
                     navigator.msGetUserMedia);

  navigator.getMedia(
  { 
  video: true, 
  audio: false 
  },
  function(stream) {
  if (navigator.mozGetUserMedia) { 
    video.mozSrcObject = stream;
  } else {
    var vendorURL = window.URL || window.webkitURL;
    video.src = vendorURL ? vendorURL.createObjectURL(stream) : stream;
  }
  video.play();
  },
  function(err) {
  console.log("An error occured! " + err);
  }
  );

  video.addEventListener('canplay', function(ev){
  if (!streaming) {
  height = video.videoHeight / (video.videoWidth/width);
  video.setAttribute('width', width);
  video.setAttribute('height', height);
  canvas.setAttribute('width', width);
  canvas.setAttribute('height', height);
  streaming = true;
  }
  }, false);

function takepicture() {
 canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(video, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
}

startbutton.addEventListener('click', function(ev){
takepicture();
ev.preventDefault();
}, false);

})();


</script>
<style>
html {
background: #111111;
height: 100%;
background: linear-gradient( #333, #000);
}
canvas {
display: none;
}
video, img, #startbutton {
display: block;
float: left;
border: 10px solid #fff;
border-radius: 10px;
}
#startbutton {
background: green;
border: none;
color: #fff;
margin: 100px 20px 20px 20px;
padding: 10px 20px;
font-size: 20px;
}
#container {
overflow: hidden;
width: 880px;
margin: 20px auto;
}
</style>
</head>
<body>
<video id="video"></video>
<button id="startbutton">Take photo</button>
<canvas id="canvas"></canvas>
<img src="http://placekitten.com/g/200/150" id="photo" alt="photo">
</body>
</html>

1 个答案:

答案 0 :(得分:1)

这是因为您的脚本正在尝试访问尚未创建的html元素。从上到下阅读HTML。将您的脚本移动到页面正文中,或者告诉它在整个页面加载之前不要执行。

当我将脚本移动到主体而不是页面的头部时,它对我来说很好。