const media = navigator.mediaDevices;通过原型链可以查找到一些方法,如下图所示:
navigator.mediaDevices.getDisplayMedia({ video: true, });在这段代码中,请求获取包含视频流的媒体许可,并将其存储在名为 stream 的变量中,以便后续使用。这个流可以用于在网页上显示屏幕共享或进行其他媒体处理操作。
<body> <button>共享屏幕</button> <script> const button = document.querySelector("button"); button.addEventListener("click", async () => { const stream = await navigator.mediaDevices.getDisplayMedia({ video: true, }); }); </script> </body>通过点击 button 按钮后会如下图所示效果:
const types = [ "video/webm", "audio/webm", "video/webm;codecs=vp8", "video/webm;codecs=daala", "video/webm;codecs=h264", "audio/webm;codecs=opus", "video/mpeg", ];通过这种方式来查看当前浏览器是否支持该类型,如下代码所示:
const mime = MediaRecorder.isTypeSupported("video/webm;codecs=h264") ? "video/webm;codecs=h264" : "video/webm";结果如下所示:
const mediaRecorder = new MediaRecorder(stream, { mimeType: mime });在这段代码里面,执行 new 关键字实例化 MediaRecorder 对象。我们可以通过监听它的事件来进行不同的操作,如下代码所示:
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(); });接下来我们来看看段代码的详细步骤:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>堆代码 duidaima.com</title> </head> <body> <button>共享屏幕</button> <script> const button = document.querySelector("button"); button.addEventListener("click", async () => { const stream = await navigator.mediaDevices.getDisplayMedia({ video: true, }); 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(); }); </script> </body> </html>完整效果如下图所示:
-const button = document.querySelector("button"); -button.addEventListener("click", async () => { +const body = document.body; +body.addEventListener("click", async () => {紧接着将代码复制粘贴到浏览器控制台上面,并点击页面的空白处:
通过这种方式就实现了一种屏幕录制或者屏幕分享的功能了。