navigator.getUserMedia
note:该方法已经被弃用,但是目前很多浏览器都支持!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>navigator.getUserMedia</title>
</head>
<body>
<button onclick="startCamre()">开启摄像头</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 startCamre(){
navigator.getUserMedia(
{
video:true,
audio:true
},
function(stream){
//创建video元素
var video = document.createElement("video");
video.id = "myvideo";
//指定src
if (window.URL) {
console.log(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>
注意:该案例中使用localhost || 127.0.0.1 是可以正常访问的,但是使用http://ip方式访问时因为没有证书会报错
这里需要把http请求换成https的方式进行请求
MediaDevices.getUserMedia()
这是最新的方法 – 推荐使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MediaDevices.getUserMedia</title>
</head>
<body>
<video src=""></video>
<script>
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
//
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function(constraints) {
var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
return new Promise(function(resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
}
}
window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);
var mediaOpts = {
audio: false,
video: true,
}
function successFunc(stream) {
var video = document.querySelector('video');
if ("srcObject" in video) {
video.srcObject = stream
} else {
video.src = window.URL && window.URL.createObjectURL(stream) || stream
}
video.play();
}
function errorFunc(err) {
alert(err.name);
}
navigator.getUserMedia(mediaOpts, successFunc, errorFunc);
</script>
</body>
</html>