html5调用摄像头

1. 页面代码

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
	<div id="contentHolder">
		<video id="video" width="320" height="320" autoplay="autoplay"></video>
		<button id="snap" style="display: none"></button>
		<canvas style="display: none" id="canvas" width="320" height="320"></canvas>
	</div>
</body>
</html>

 2.js代码

window.addEventListener('DOMContentLoaded', function () {
        var canvas = document.getElementById('canvas'),
			context = canvas.getContext('2d'),
			video = document.getElementById('video'),
			videoObj = { video : true },
			errBack = function (err) {
				console.log('Video capture error : ' , err.code );
			};
        navigator.getUserMedia = navigator.getUserMedia ||  navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
        navigator.getUserMedia(videoObj, function (stream) {
			video.src = window.webkitURL.createObjectURL(stream);
			video.play();
		}, errBack);
	});

 3. 设备拥有多个摄像头的情况下如何开启其他摄像头

var audios = [], videos=[]

function gotSources(sourceInfos) {
  for (var i = 0; i != sourceInfos.length; ++i) {
    var sourceInfo = sourceInfos[i];
     if (sourceInfo.kind === 'audio') {
         audios.push(sourceInfo.id);
    } else if (sourceInfo.kind === 'video') {
         videos.push(sourceInfo.id);
    } else {
       console.log('some other kind of source: ', sourceInfo);
    }   
  }
}

if (typeof MediaStreamTrack === 'undefined'){
  alert('This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
} else {
  MediaStreamTrack.getSources(gotSources);
}

function successCallback(stream) {
  window.stream = stream; // make stream available to console
  videoElement.src = window.URL.createObjectURL(stream);
  videoElement.play();
}

function errorCallback(error){
  console.log("navigator.getUserMedia error: ", error);
}

function start(){
  if (!!window.stream) {
    videoElement.src = null;
    window.stream.stop();
  }
  var constraints = {
    audio: {
      optional: [{sourceId: audios[0]}]
    },
    video: {
      optional: [{sourceId: videos[0]}]
    }
  };
  navigator.getUserMedia(constraints, successCallback, errorCallback);
}

start();

相关推荐