WebRTC(目前火狐浏览器支持)
作用
- 调用系统的摄像头和麦克风
使用
navigator.getUserMedia(options, success, error)
-
options
{ video:true/false, audio:true/false }
MediaStream
成功后的回调函自动传入该对象作为参数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebRTC</title>
</head>
<body>
<button onclick="startCam()">开启摄像头</button>
<hr>
<div id="box">
<button id="btn" style="display:none">拍照</button>
<br>
</div>
<br>
<div id="cam_box"></div>
<script>
navigator.getUserMedia || (navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia);
function startCam(){
navigator.getUserMedia(
{
video:true,
audio:true
},
function(stream){
//创建video元素
var video = document.createElement("video");
video.id = "myvideo";
//指定src
if (window.URL) {
video.src = window.URL.createObjectURL(stream);
} else {
video.src = stream;
}
//添加video到页面
document.querySelector("#box").appendChild(video);
btn.style.display = "block";
//视频播放
video.play();
},
function(error){
console.log(error);
}
)
}
var btn = document.querySelector("#btn");
btn.onclick = function(){
var canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 480;
var cxt = canvas.getContext("2d");
cxt.drawImage(document.querySelector("#myvideo"), 0, 0, 640, 480);
document.querySelector("#cam_box").appendChild(canvas);
}
</script>
</body>
</html>