<%--
  Created by IntelliJ IDEA.
  User: ZJW
  Date: 2019/5/3
  Time: 17:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<!-- saved from url=(0029)https://bingxl.cn/webrtc.html -->
<html lang="ZH-CN"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>web RTC 测试</title>
    <link rel="shortcut icon" href="http://dsada1.oss-cn-beijing.aliyuncs.com/img/xicon.png" type="image/x-icon">
    <style>
        .booth {
            width:400px;

            background:#ccc;
            border: 10px solid #ddd;
            margin: 0 auto;
        }
    </style>
</head>
<body>
<article>
    <section>
        <video id="video" width="320" height="240"></video>
    </section>
    <section>
        <audio id="audio"></audio>
    </section>
    <button id="btn">拍照</button>
    <section>
        <canvas id="canvas" width="320" height="240"></canvas>
    </section>
</article>

<script src=""></script><script>
    let convas = document.querySelector("#canvas"); //
    let video = document.querySelector("#video");
    let audio = document.querySelector("audio");
    let img = document.querySelector("#img");
    let btn = document.querySelector("button");
    let context = canvas.getContext('2d');
    let width = 320; //视频和canvas的宽度
    let height = 0; //
    let streaming = false; // 是否开始捕获媒体

    // 获取用户媒体,包含视频和音频
    navigator.mediaDevices.getUserMedia({video: true, audio: false})
        .then(stream => {
            video.srcObject = stream; // 将捕获的视频流传递给video  放弃window.URL.createObjectURL(stream)的使用
            video.play(); //  播放视频
            audio.srcObject = stream;
            audio.play();
        });

    function tackcapture() {
        // 需要判断媒体流是否就绪
        if(streaming){
            context.drawImage(video, 0, 0, 350, 200);// 将视频画面捕捉后绘制到canvas里面
            img.src = canvas.toDataURL('image/png');// 将canvas的数据传送到img里
        }
    }
    btn.addEventListener('click',tackcapture,false); // 按钮点击事件
    // 监听视频流就位事件,即视频可以播放了
    video.addEventListener('canplay', function(ev){
        if (!streaming) {
            height = video.videoHeight / (video.videoWidth/width);

            video.setAttribute('width', width);
            video.setAttribute('height', height);
            canvas.setAttribute('width', width);
            canvas.setAttribute('height', height);
            streaming = true;
        }
    }, false);
</script>
</body></html>
