webrtc学习笔记

参考极客时间做了一个拍照的demo

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0
        }

        canvas {
            margin: 40px auto;
        }
    </style>
</head>

<body>

    <video autoplay playsinline></video>
    <canvas width="600" height="450"></canvas>
    <button>拍照</button>
    <button>下载</button>
    <script>

        'use strict';

        var canvas = document.getElementsByTagName('canvas')[0];
        var ctx = canvas.getContext('2d');
        var btn = document.getElementsByTagName('button')

        function draw() {
            ctx.drawImage(localVideo, 0, 0, canvas.width, canvas.height)
        }
        function download() {
            var url = canvas.toDataURL("image/jpeg")
            var a = document.createElement('a');
            document.body.appendChild(a)
            a.href = url;
            a.download = 'picture';
            a.click()
            document.body.removeChild(a)
        }
        btn[0].onclick = function () {
            draw()
        }
        btn[1].onclick = function () {
            download()
        }

        const mediaStreamContrains = {
            video: true
        };

        const localVideo = document.querySelector('video');

        function gotLocalMediaStream(mediaStream) {
            localVideo.srcObject = mediaStream;
        }

        function handleLocalMediaStreamError(error) {
            console.log('navigator.getUserMedia error: ', error);
        }

        navigator.mediaDevices.getUserMedia(mediaStreamContrains).then(
            gotLocalMediaStream
        ).catch(
            handleLocalMediaStreamError
        );
    </script>




</body>

</html>

navigator.mediaDevices.getUserMedia(constraints)方法返回一个promise对象,constraints是一个对象,可以设置视频,音频的属性,然后把返回的六对象赋值给video标签的srcObject即可显示图像,再调用canvas绘制图像及生成url即可下载图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值