源代码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>摄像头调用</title>
</head>
<body>
<video id="v"></video>
<!--拍照按钮-->
<div>
<button id="capture">拍照</button>
</div>
<!--描绘video截图-->
<canvas id="canvas" width="480" height="320"></canvas>
<div>
<!-- 声明一个按钮 用来触发下载图片到本地-->
<input type="button" id="btnsavaImg" value="保存图片到本地" onClick="Download()"/>
</div>
<script>
var video = document.getElementById('v');
var canvas = document.getElementById('canvas');
var capture = document.getElementById('capture');
var context = canvas.getContext('2d');
!(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 promise = navigator.mediaDevices.getUserMedia(constraints);
promise.then(stream => {
let v = document.getElementById('v');
// 旧的浏览器可能没有srcObject
if ("srcObject" in v) {
v.srcObject = stream;
} else {
// 防止再新的浏览器里使用它,应为它已经不再支持了
v.src = window.URL.createObjectURL(stream);
}
v.onloadedmetadata = function(e) {
v.play();
};
}).catch(err => {
console.error(err.name + ": " + err.message);
})
})();
capture.addEventListener('click', function() {
// 将video画面描绘在canvas画布上
context.drawImage(video, 0, 0, 480, 320);
})
</script>
<script type="text/javascript">
function Download() {
//cavas 保存图片到本地 js 实现
//------------------------------------------------------------------------
//1.确定图片的类型 获取到的图片格式 data:image/Png;base64,......
var type = 'jpg'; //你想要什么图片格式 就选什么吧
var imgdata = canvas.toDataURL(type);
//2.0 将mime-type改为image/octet-stream,强制让浏览器下载
var fixtype = function(type) {
type = type.toLocaleLowerCase().replace(/jpg/i, 'jpeg');
var r = type.match(/png|jpeg|bmp|gif/)[0];
return 'image/' + r;
};
imgdata = imgdata.replace(fixtype(type), 'image/octet-stream');
//3.0 将图片保存到本地
var savaFile = function(data, filename) {
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = data;
save_link.download = filename;
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(event);
};
var filename = '图像_' + new Date().getSeconds() + '.' + type;
//我想用当前秒是可以解决重名的问题了 不行你就换成毫秒
savaFile(imgdata, filename);
}
</script>
</body>
</html>