html5 摄像头的调用

 <!DOCTYPE html>
<html>
<head>
<title>摄像头调用</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" charset="utf-8" />
<style type="text/css">
video,canvas{
margin-top: 10px;
}
</style>
</head>
<body>
<input type="button" title="开启摄像头" value="开启摄像头" onclick="getMedia();" />
<input type="button" title="关闭摄像头" value="关闭摄像头" onclick="shutdown()"><br/>
<video height="200px" autoplay="autoplay" poster="cover.png" ></video><hr/> //poster是video的封面图片,可以自己加一个,也可以直接去掉 <input type="button" title="拍照" value="拍照" onclick="getPhoto();"/><br/>
<canvas id="canvas1" height="200px" ></canvas> <script type="text/javascript">
var video = document.querySelector('video'); var canvas1 = document.getElementById('canvas1');
var context1 = canvas1.getContext('2d'); navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.mozURL || window.msUR; var exArray = []; //存储设备源ID
MediaStreamTrack.getSources(function (sourceInfos) {
for (var i = 0; i != sourceInfos.length; ++i) {
var sourceInfo = sourceInfos[i];
//这里会遍历audio,video,所以要加以区分
if (sourceInfo.kind === 'video') {
exArray.push(sourceInfo.id);
}
}
}); function getMedia() {
if (navigator.getUserMedia) {
navigator.getUserMedia({
'video': {
'optional': [{
'sourceId': exArray[1] //0为前置摄像头,1为后置
}]
},
'audio':false //关闭声音
}, successFunc, errorFunc); //success是获取成功的回调函数
}
else {
alert('Native device media streaming (getUserMedia) not supported in this browser.');
}
}
function shutdown() {
successFunc(null);
}
function successFunc(stream) {
//alert('Succeed to get media!');
if (video.mozSrcObject !== undefined) {
//Firefox中,video.mozSrcObject最初为null,而不是未定义的,我们可以靠这个来检测Firefox的支持
video.mozSrcObject = stream;
}
else {
video.src = window.URL && window.URL.createObjectURL(stream) || stream;
}
}
function errorFunc(e) {
alert('Error!'+e);
}
//拍照
function getPhoto() {
context1.drawImage(video, 0, 0,270,200); //将video对象内指定的区域捕捉绘制到画布上指定的区域,实现拍照。
}
</script>
</body>
</html>
上一篇:root运行chrome


下一篇:CGI杂谈