美文网首页
02.webRTC使用浏览器给自己拍照

02.webRTC使用浏览器给自己拍照

作者: 讲武德的年轻人 | 来源:发表于2020-01-11 11:35 被阅读0次
  • html
<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>
  • client.js

'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);

相关文章

网友评论

      本文标题:02.webRTC使用浏览器给自己拍照

      本文链接:https://www.haomeiwen.com/subject/huvvactx.html