【js】navigator.mediaDevices.getDisplayMedia实现屏幕共享:

文章目录

        • 一、效果图:
        • 二、实现思路:
        • 三、实现代码:


一、效果图:

【js】navigator.mediaDevices.getDisplayMedia实现屏幕共享:_第1张图片

二、实现思路:

文档:
【MDN】https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/mediaDevices
web技术分享| WebRTC 实现屏幕共享
面试官:纯前端如何实现录屏并保存视频到本地?

三、实现代码:
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>

<body>
  <div>
    <video id="gum-local" autoplay playsinline muted style="width: 400px;height: 400px;border: 1px solid red;"></video>
    <button id="startButton" disabled>Start</button>
    <div id="errorMsg"></div>
  </div>
  <script>
    const startButton = document.getElementById('startButton');
    if ((navigator.mediaDevices && 'getDisplayMedia' in navigator.mediaDevices)) {
      startButton.disabled = false;
    } else {
      errorMsg('不支持getDisplayMedia');
    }
    startButton.addEventListener('click', () => {
      navigator.mediaDevices.getDisplayMedia({ video: true }).then(handleSuccess, handleError);
    });

    function handleSuccess(stream) {
      startButton.disabled = true;

      // 将共享屏幕内容显示到video里面
      const video = document.querySelector('video');
      video.srcObject = stream;

      // 检测用户已停止共享屏幕,通过浏览器UI共享屏幕。
      stream.getVideoTracks()[0].addEventListener('ended', () => {
        errorMsg('用户已结束共享屏幕');
        startButton.disabled = false;
      });

      // const mime = MediaRecorder.isTypeSupported("video/webm;codecs=h264") ? "video/webm;codecs=h264" : "video/webm";
      // const mediaRecorder = new MediaRecorder(stream, { mimeType: mime });
      // const chunks = [];
      // mediaRecorder.addEventListener("dataavailable", function (e) { chunks.push(e.data); });
      // mediaRecorder.addEventListener("stop", () => {
      //   const blob = new Blob(chunks, { type: chunks[0].type });
      //   const url = URL.createObjectURL(blob);
      //   const a = document.createElement("a");
      //   a.href = url;
      //   a.download = "video.webm";
      //   a.click();
      // });
      // mediaRecorder.start();
    }

    function handleError(error) {
      errorMsg(`getDisplayMedia error: ${error.name}`, error);
    }

    function errorMsg(msg, error) {
      const errorElement = document.querySelector('#errorMsg');
      errorElement.innerHTML += `<p>${msg}</p>`;
      if (typeof error !== 'undefined') {
        console.error(error);
      }
    }
  </script>
</body>

</html>

你可能感兴趣的:(JavaScript,javascript,开发语言,ecmascript)