MediaDevices.getUserMedia() 会提示用户给予使用媒体输入的许可,媒体输入会产生一个MediaStream,里面包含了请求的媒体类型的轨道。此流可以包含一个视频轨道(来自硬件或者虚拟视频源,比如相机、视频采集设备和屏幕共享服务等等)、一个音频轨道(同样来自硬件或虚拟音频源,比如麦克风、A/D转换器等等),也可能是其它轨道类型。
看一下我实现的效果图吧
我是这样写的demo代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>摄像拍照</title>
</head>
<body>
<video id="video" width="640" height="480" autoplay></video>
<button id="snap">拍照</button>
<button id="save">保存</button>
<canvas id="canvas" width="640" height="480"></canvas>
<script>
// Grab elements, create settings, etc.
var count=0;//是否点击过拍照
var video = document.getElementById('video');
// Get access to the camera!
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// Not adding `{ audio: true }` since we only want video now
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
//video.src = window.URL.createObjectURL(stream);
video.srcObject = stream;
video.play();
});
}
// Elements for taking the snapshot
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');
// Trigger photo take
var snap= document.getElementById("snap");
snap.addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
count++;
if(video.paused){
snap.innerText="拍照"
video.play();
}else{
snap.innerText="重新拍一张呀"
video.pause();
}
});
var save=document.getElementById("save");
save.addEventListener("click",function(){
if(count===0){
alert("请先拍一张帅气照")
}else{
var a = document.createElement('a');
console.log(context.drawImage);
a.setAttribute('href', canvas.toDataURL()); //toDataUrl:将canvas画布信息转化为base64格式图片
a.setAttribute('download', 'downImg') //这个是必须的,否则会报错
a.setAttribute('target', '_self');
a.click()
}
})
</script>
</body>
</html>
更多使用看MDN https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia
|