html5直接调用web api获取摄像头xi一共信息,种实现方式,
1、使用navigator.getUserMedia(该特性已经从 Web 标准中删除,虽然一些浏览器目前仍然支持它,但也许会在未来的某个时间停止支持,请尽量不要使用该特性),前面一种已经从 Web 标准中删除,仅为了向后兼容而存在,
2、是使用navigator.mediaDevices.getUserMedia(推荐使用),这两种方法 Safari 貌似都不支持。。。。
拍照
思路是设置一个标志变量 videoPlaying 看看是否 video 有在 play,监听拍照按钮的点击事件,如果videoPlaying 为 true ,使用一个canvas 获取 video 的宽高(默认 canvas 是不显示的),然后使用 canvas 的drawImage,然后使用 canvas 的 toDataURL返回一个 data url,将这个 url,设置在一个 img 标签上即可
第一种方法navigator.getUserMedia用法详见 mdn ,代码如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拍照1</title>
</head>
<body>
<button id="take">拍照</button>
<br />
<video id="v" style="width: 640px;height: 480px;"></video>
<canvas id="canvas" style="display:none;"></canvas>
<br />
<img src="http://placehold.it/640&text=Your%20image%20here%20..." id="photo" alt="photo">
<script>
!(function () {
function userMedia() {
return navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia || null;
}
if (userMedia()) {
let videoPlaying = false;
let constraints = {
video: true,
audio: false
};
let video = document.getElementById('v');
let media = navigator.getUserMedia(constraints, function (stream) {
let url = window.URL || window.webkitURL;
video.src = url ? url.createObjectURL(stream) : stream;
video.play();
videoPlaying = true;
}, function (error) {
console.log("ERROR");
console.log(error);
});
document.getElementById('take').addEventListener('click', function () {
if (videoPlaying) {
let canvas = document.getElementById('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0);
let data = canvas.toDataURL('image/webp');
document.getElementById('photo').setAttribute('src', data);
}
}, false);
} else {
console.log("不支持");
}
})();
</script>
</body>
</html>
第二种navigator.mediaDevices.getUserMedia
实现方法:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拍照2</title>
</head>
<body>
<button id="take">拍照</button>
<br />
<video id="v" style="width: 640px;height: 480px;"></video>
<canvas id="canvas" style="display:none;"></canvas>
<br />
<img src="http://placehold.it/640&text=Your%20image%20here%20..." id="photo" alt="photo">
<script>
!(function () {
// 老的浏览器可能根本没有实现 mediaDevices,所以我们可以先设置一个空的对象
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function (constraints) {
// 首先,如果有getUserMedia的话,就获得它
var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
// 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
// 否则,为老的navigator.getUserMedia方法包裹一个Promise
return new Promise(function (resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
}
}
const constraints = {
video: true,
audio: false
};
let videoPlaying = false;
let v = document.getElementById('v');
let promise = navigator.mediaDevices.getUserMedia(constraints);
promise.then(stream => {
// 旧的浏览器可能没有srcObject
if ("srcObject" in v) {
v.srcObject = stream;
} else {
// 防止再新的浏览器里使用它,应为它已经不再支持了
v.src = window.URL.createObjectURL(stream);
}
v.onloadedmetadata = function (e) {
v.play();
videoPlaying = true;
};
}).catch(err => {
console.error(err.name + ": " + err.message);
})
document.getElementById('take').addEventListener('click', function () {
if (videoPlaying) {
let canvas = document.getElementById('canvas');
canvas.width = v.videoWidth;
canvas.height = v.videoHeight;
canvas.getContext('2d').drawImage(v, 0, 0);
let data = canvas.toDataURL('image/webp');
document.getElementById('photo').setAttribute('src', data);
}
}, false);
})();
</script>
</body>
</html>
以上来源于:https://blog.csdn.net/qq_33699981/article/details/80210614
另外的方法:
Html
<p>
<button onclick="openMedia()">打开</button>
<button onclick="closeMedia()">关闭</button>
<button onclick="drawMedia()">截取</button>
</p>
<video id="video" class="bg"></video>
<canvas id="qr-canvas"></canvas>
Javascript
<script type="text/javascript">var video = document.querySelector('video');
var text = document.getElementById('text');
var canvas1 = document.getElementById('qr-canvas');
var context1 = canvas1.getContext('2d');
var mediaStreamTrack;
// 一堆兼容代码
window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function(constraints) {
var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
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);
});
}
}
//摄像头调用配置
var mediaOpts = {
audio: false,
video: true,
video: {
facingMode: "environment"
} // 或者 "user"
// video: { width: 1280, height: 720 }
// video: { facingMode: { exact: "environment" } }// 或者 "user"
}
// 回调
function successFunc(stream) {
mediaStreamTrack = stream;
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);
}
// 正式启动摄像头
function openMedia() {
navigator.mediaDevices.getUserMedia(mediaOpts).then(successFunc).
catch(errorFunc);
}
//关闭摄像头
function closeMedia() {
mediaStreamTrack.getVideoTracks().forEach(function(track) {
track.stop();
context1.clearRect(0, 0, context1.width, context1.height); //清除画布
});
}
//截取视频
function drawMedia() {
canvas1.setAttribute("width", video.videoWidth);
canvas1.setAttribute("height", video.videoHeight);
context1.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
}
</script>
以上来源于:https://www.jb51.net/article/160015.htm
另外:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
<title>Document1</title>
<style type='text/css'>
* { margin: 0; padding: 0; }
html, body { height: 100%; }
.flex { display: flex; }
.flex-row { flex-direction: row; justify-content: space-around; align-items: center; }
.flex-column { flex-direction: column; justify-content: flex-start; align-items: center; }
body { overflow: auto; background: #fff; }
.title { width: 920px; padding: 30px; align-items: flex-end; }
.title h1 { padding-bottom: 20px; font-size: 38px; color: #ffffff; text-shadow: 0 1px 3px #222222; }
.title p { font-size: 18px; color: #f5f5f5; text-shadow: 0 1px 3px #565656; }
.wrap { width: 1220px; }
.wrap .reference { position: relative; padding: 10px; background-color: rgba(255, 255, 255, 0); border-radius: 10px; box-shadow: 0 0 20px #a1a19f; }
.wrap .reference img.face { display: block; width: 320px; height: auto; border-radius: 10px; }
.wrap .reference img.toggle { position: absolute; right: 10px; top: 10px; width: 50px; height: 50px; }
.wrap .scan video { background-color: rgba(0, 0, 0, .8); border-radius: 10px; }
.wrap .control { justify-content: space-around; height: 456px; padding: 0 20px; }
.wrap .control p { width: 160px; height: 60px; background-color: #f9f9f9; text-align: center; line-height: 60px; color: #ffffff; font-size: 24px; border-radius: 8px; cursor: pointer; box-shadow: -8px -8px 150px -8px #b2b3b5 inset, 0 0 5px #222222; text-shadow: 0 0 1px #222222; transition: .5s; }
.wrap .control p:hover { box-shadow: -8px -8px 150px -8px #50c4f1 inset, 0 0 5px #ffffff; }
.wrap .scan { position: relative; overflow: hidden; }
.wrap .scan .strainer { position: absolute; top: 10px; width: 320px; z-index: 999; height: 3px; }
.wrap .scan .capture { width: 320px; height: 456px; }
.wrap .scan .strainer.on { background: linear-gradient(to left, transparent, #0bffb2, transparent); animation: scan 1s linear infinite; }
@keyframes scan {
0% { top: 10px; }
50% { top: 456px; }
100% { top: 10px; }
}
</style>
<script type="text/javascript" src="vconsole.min.js"></script>
</head>
<body>
<div class="title flex flex-column">
</div>
<div class="wrap flex flex-row">
<div class="control flex flex-column">
<p class="open">开启摄像头</p>
<p class="recognition">显示到Canvas</p>
<p class="close">关闭摄像头</p>
</div>
<div class="scan reference">
<div class="strainer"></div>
<video class="capture" width="320" height="456" src=""></video>
</div>
</div>
<script type="text/javascript">
var buffer;
var oCapture = document.querySelector(".capture"),
open = document.querySelector(".open"),
recognition = document.querySelector(".recognition"),
close = document.querySelector(".close");
var control = document.querySelector(".control");
window.navigator.getUserMedia = navigator.getUserMedia || navigator.webKitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
function invokingCarera(){
if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){
navigator.mediaDevices.getUserMedia({
'audio':true,
'video':{ 'facingMode': "user" }//调用前置摄像头,后置摄像头使用video: { facingMode: { exact: "environment" } }
})
.then(function(mediaStream) {console.log(555);getVideoStream(mediaStream)})
.catch(function(error) { console.log(666);console.log(error) })
}else if(navigator.getUserMedia){
navigator.getUserMedia({
'video':true,
'audio':true
},getVideoStream,getFail)
}else{
alert('不支持摄像头调用!')
}
}
//调用成功
function getVideoStream(stream){
buffer = stream;
if(oCapture.mozSrcObject !== undefined){
oCapture.mozSrcObject = buffer;
}else{
oCapture.src = window.URL && window.URL.createObjectURL(buffer);
}
oCapture.play();
}
function getFail(){
}
recognition.onclick = function(){
}
control.addEventListener('click',function(e){
e = e || window.event;
var className = e.target.className;
switch(className){
case 'open':
invokingCarera();
break;
case 'close':
closeCamera();
break;
case 'recognition':
screenShot();
break;
default:
break;
}
})
function closeCamera(){
buffer&&buffer.getTracks()[1].stop();//关闭摄像头
}
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
function screenShot(){
var canvas = document.createElement('canvas');
canvas.width=320,canvas.height = 456;
document.querySelector(".wrap").appendChild(canvas);
var ctx = canvas.getContext('2d');
function drawVideo(){
ctx.drawImage(oCapture,0,0,320,456);
ctx.font = "30px sans-serif";
ctx.fillStyle = "blue";
ctx.fillText("请眨眼", 50, 50);
requestAnimationFrame(drawVideo);
}
window.requestAnimationFrame(drawVideo);
}
</script>
</body>
</html>
以上原文链接:https://blog.csdn.net/w20101310/article/details/78251938