美文网首页
WebRTC navigator.getUserMedia()

WebRTC navigator.getUserMedia()

作者: 飞鱼_JS | 来源:发表于2017-06-13 19:14 被阅读0次
    2017-06-13_191243.png
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>WebRTC</title>
    </head>
    <body>
        <button onclick="startCam()">开启摄像头</button>
        <hr>
        <div id="box">
            <button id="btn" style="display:none">拍照</button>
            <br>
        </div>
    
        <br>
    
        <div id="cam_box"></div>
    
        <script>
    //兼容处理
            navigator.getUserMedia || (navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia);
    
            function startCam(){
                navigator.getUserMedia(
                {
                    video:true,
                    audio:true
                },
                function(stream){
                    //创建video元素
                    var video = document.createElement("video");
                    video.id = "myvideo";
                    //指定src
                    if (window.URL) {
                        video.src = window.URL.createObjectURL(stream);
                    } else {
                        video.src = stream;
                    }
                    //添加video到页面
                    document.querySelector("#box").appendChild(video);
                    btn.style.display = "block";
    
                    //视频播放
                    video.play();
                },
                function(error){
                    console.log(error);
                }
                )
            }
            var btn = document.querySelector("#btn");
            btn.onclick = function(){
                var canvas = document.createElement("canvas");
                canvas.width = 640;
                canvas.height = 480;
                var cxt = canvas.getContext("2d");
                cxt.drawImage(document.querySelector("#myvideo"), 0, 0, 640, 480);
                document.querySelector("#cam_box").appendChild(canvas);
            }
        </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:WebRTC navigator.getUserMedia()

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