<html>
<head>
<title>WebRTC take picture</title>
</head>
<body>
<video autoplay playsinline id="player"></video><br>
<button id="TakePhoto">Take</button>
<div>
<button id="save"> 保存 </button>
</div>
<canvas id="picture"></canvas>
<script src="./js/client.js"></script>
<script>
// 调用 Canvas 上下文的 drawImage 方法,从视频流中抓取当时正在显示的图片了
document.getElementById('TakePhoto').onclick = function(){
var picture = document.querySelector('canvas#picture');
picture.width = 640;
picture.height = 360;
picture.getContext('2d').drawImage(videoplay, 0, 0, picture.width, picture.height);
}
function downLoad(url){
var oA = document.createElement("a");
oA.download = 'photo';// 设置下载的文件名,默认是'下载'
oA.href = url;
document.body.appendChild(oA);
oA.click();
oA.remove(); // 下载之后把创建的元素删除
}
// 将截取的图片保存起来
document.querySelector("button#save").onclick = function (){
downLoad(picture.toDataURL("image/jpeg"));
}
</script>
</body>
</html>
'use strict'
// 获取 HTML 页面中的 video 标签
var videoplay = document.querySelector('video#player');
// 播放视频流
function gotMediaStream(stream){
videoplay.srcObject = stream;
}
function handleError(err){
console.log('getUserMedia error:', err);
}
// 对采集的数据做一些限制
var constraints = {
video : {
width: 1280,
height: 720,
frameRate:15,
},
audio : false
}
// 采集音视频数据流
navigator.mediaDevices.getUserMedia(constraints)
.then(gotMediaStream)
.catch(handleError);
网友评论