HTML5利用WebRTC的getUserMedia获取摄像头信息模拟拍照及视频(完整示例)

HTML5可以通过调用navigator.getUserMedia来获取手机设备摄像头,兼容性写法如下

window.navigator.getUserMedia = navigator.getUserMedia || navigator.webKitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  • 1

但是navigator.getUserMediau已经从 Web 标准中删除,虽然部分浏览器可以使用,生产环境中还是要做好兼容。新的API更替为MediaDevices.getUserMedia。MediaDevices.getUserMedia可以通过video的facingMode属性指定调用手机的前置或后置摄像头

video:{ 'facingMode': "user" }//调用前置摄像头
video: { facingMode: { exact: "environment" } }//后置
  • 1
  • 2

具体代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
    <title>Document1</title>
    <style type='text/css'>
        * { margin: 0; padding: 0; }

        html, body { height: 100%; }

        .flex { display: flex; }

        .flex-row { flex-direction: row; justify-content: space-around; align-items: center; }

        .flex-column { flex-direction: column; justify-content: flex-start; align-items: center; }

        body { overflow: auto; background: #fff; }

        .title { width: 920px; padding: 30px; align-items: flex-end; }

        .title h1 { padding-bottom: 20px; font-size: 38px; color: #ffffff; text-shadow: 0 1px 3px #222222; }

        .title p { font-size: 18px; color: #f5f5f5; text-shadow: 0 1px 3px #565656; }

        .wrap { width: 1220px; }

        .wrap .reference { position: relative; padding: 10px; background-color: rgba(255, 255, 255, 0); border-radius: 10px; box-shadow: 0 0 20px #a1a19f; }

        .wrap .reference img.face { display: block; width: 320px; height: auto; border-radius: 10px; }

        .wrap .reference img.toggle { position: absolute; right: 10px; top: 10px; width: 50px; height: 50px; }

        .wrap .scan video { background-color: rgba(0, 0, 0, .8); border-radius: 10px; }

        .wrap .control { justify-content: space-around; height: 456px; padding: 0 20px; }

        .wrap .control p { width: 160px; height: 60px; background-color: #f9f9f9; text-align: center; line-height: 60px; color: #ffffff; font-size: 24px; border-radius: 8px; cursor: pointer; box-shadow: -8px -8px 150px -8px #b2b3b5 inset, 0 0 5px #222222; text-shadow: 0 0 1px #222222; transition: .5s; }

        .wrap .control p:hover { box-shadow: -8px -8px 150px -8px #50c4f1 inset, 0 0 5px #ffffff; }

        .wrap .scan { position: relative; overflow: hidden; }

        .wrap .scan .strainer { position: absolute; top: 10px; width: 320px; z-index: 999; height: 3px; }

        .wrap .scan .capture { width: 320px; height: 456px; }

        .wrap .scan .strainer.on { background: linear-gradient(to left, transparent, #0bffb2, transparent); animation: scan 1s linear infinite; }

        @keyframes scan {
            0% { top: 10px; }
            50% { top: 456px; }
            100% { top: 10px; }
        }

    </style>
    <script type="text/javascript" src="vconsole.min.js"></script>
</head>
<body>
    <div class="title flex flex-column">
</div>
<div class="wrap flex flex-row">
    <div class="control flex flex-column">
        <p class="open">开启摄像头</p>
        <p class="recognition">显示到Canvas</p>
        <p class="close">关闭摄像头</p>
    </div>
    <div class="scan reference">
        <div class="strainer"></div>
        <video class="capture" width="320" height="456" src=""></video>
    </div>

</div>

    <script type="text/javascript">
        var buffer;
        var oCapture = document.querySelector(".capture"),
        open = document.querySelector(".open"),
        recognition = document.querySelector(".recognition"),
        close = document.querySelector(".close");
        var control = document.querySelector(".control");

        window.navigator.getUserMedia = navigator.getUserMedia || navigator.webKitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

        function invokingCarera(){
            if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){
                navigator.mediaDevices.getUserMedia({
                    'audio':true,
                    'video':{ 'facingMode': "user" }//调用前置摄像头,后置摄像头使用video: { facingMode: { exact: "environment" } }
                })
                .then(function(mediaStream) {console.log(555);getVideoStream(mediaStream)})
                .catch(function(error) { console.log(666);console.log(error) })
            }else if(navigator.getUserMedia){
                navigator.getUserMedia({
                    'video':true,
                    'audio':true
                },getVideoStream,getFail)
            }else{
                alert('不支持摄像头调用!')
            }
        }
        //调用成功
        function getVideoStream(stream){
            buffer = stream;
            if(oCapture.mozSrcObject !== undefined){
                oCapture.mozSrcObject = buffer;
            }else{
                oCapture.src = window.URL && window.URL.createObjectURL(buffer);                
            }
            oCapture.play();
        }
        function getFail(){

        }
        recognition.onclick = function(){

        }
        control.addEventListener('click',function(e){
            e = e || window.event;
            var className = e.target.className;
            switch(className){
                case 'open':
                invokingCarera();
                break;
                case 'close':
                closeCamera();
                break;
                case 'recognition':
                screenShot();
                break;
                default:
                break;
            }
        })
        function closeCamera(){
            buffer&&buffer.getTracks()[1].stop();//关闭摄像头
        }        
        window.requestAnimFrame = (function(){
          return  window.requestAnimationFrame       ||
                  window.webkitRequestAnimationFrame ||
                  window.mozRequestAnimationFrame    ||
                  function( callback ){
                    window.setTimeout(callback, 1000 / 60);
                  };
        })();
        function screenShot(){
            var canvas = document.createElement('canvas');
            canvas.width=320,canvas.height = 456;
            document.querySelector(".wrap").appendChild(canvas);
            var ctx =  canvas.getContext('2d');
            function drawVideo(){
                ctx.drawImage(oCapture,0,0,320,456);
                ctx.font = "30px sans-serif";
                ctx.fillStyle = "blue";
                ctx.fillText("请眨眼", 50, 50);
                requestAnimationFrame(drawVideo);
            }
            window.requestAnimationFrame(drawVideo);
        }
    </script>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162

以上代码并没有进行太多的错误处理,比如用户拒绝授权访问摄像头或浏览器不支持等情况,生产环境使用需添加错误处理代码.

以上代码在PC端和Android手机端和微信测试通过,IOS下浏览器均不支持,据说IOS11会开放权限。

注意,以上HTML需要在HTTPS下访问方可正常工作

查看在线DEMO,如果使用微信访问可能被屏蔽,微信打开链接后点击右下角“访问原网页”

如需本地测试请使用Chrome插件:web-server;

webserver使用方法:chrome://apps > web-server > choose folder 勾选 Show Advanced Settings下Set CORS Headers即可

使用input type=”file”调用摄像头拍照可以参考camera API

 

 

转载:https://blog.csdn.net/journey191/article/details/40744015

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
如果你希望通过WebRTC技术播放网络摄像头视频流,可以参考以下步骤: 1. 获取网络摄像头视频流。 你可以使用`getUserMedia`方法获取网络摄像头视频流,代码示例如下: ``` navigator.mediaDevices.getUserMedia({ video: { deviceId: '摄像头设备ID', width: 640, height: 480, frameRate: { ideal: 15, max: 30 } }, audio: false }).then(function (stream) { // 获取视频流,后续可以通过WebRTC技术进行传输 }).catch(function (err) { // 获取视频流失败 }); ``` 在上面的示例中,我们使用`getUserMedia`方法获取网络摄像头视频流,并设置了摄像头设备ID、视频分辨率、帧率等参数。获取视频流后,你可以将其传输到远程端。 2. 使用WebRTC技术进行视频传输。 你可以使用WebRTC技术进行视频传输,代码示例如下: ``` var pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] }); pc.addStream(localStream); // 将本地视频流添加到PeerConnection中 pc.createOffer().then(function (offer) { // 创建Offer,向远程端发送视频流 return pc.setLocalDescription(offer); }).then(function () { // 将本地描述信息发送给远程端 }).catch(function (err) { // 创建Offer失败 }); pc.onicecandidate = function (event) { // 获取到ICE Candidate,将其发送给远程端 }; pc.onaddstream = function (event) { // 获取到远程视频流,可以通过video标签进行播放 var remoteVideo = document.getElementById('remote-video'); remoteVideo.srcObject = event.stream; remoteVideo.play(); }; ``` 在上面的示例中,我们使用`RTCPeerConnection`对象创建了一个PeerConnection,并通过`addStream`方法将本地视频流添加到PeerConnection中。然后,我们调用`createOffer`方法创建一个Offer,向远程端发送视频流,并将本地描述信息发送给远程端。在`onicecandidate`事件中获取到ICE Candidate,将其发送给远程端。最后,当获取到远程视频流时,我们可以通过`video`标签进行播放。 需要注意的是,这里的代码示例仅仅是一个基本的实现示例,具体实现过程还需要根据你的实际情况进行相应的调整和修改。同时,你需要确保网络摄像头和前端都能够访问到该地址。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值