屏幕录制需要使用两个谷歌提供的接口:
MediaDevices 和 MediaRecorder
使用屏幕捕获API:https://developer.mozilla.org/zh-CN/docs/Web/API/Screen_Capture_API/Using_Screen_Capture
代码实现:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><video class="video" width="600px" controls></video><button class="record-btn" onclick="record()">record</button><script>let btn = document.querySelector('.record-btn')async function record() {let stream = await navigator.mediaDevices.getDisplayMedia({video: true})// 需要更好的浏览器支持const mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9") ? "video/webm; codecs=vp9" : "video/webm"let mediaRecorder = new MediaRecorder(stream, {mimeType: mime})let chunks = []// 监听数据提供事件mediaRecorder.addEventListener('dataavailable', function (e) {console.log(e);chunks.push(e.data)})// 监听停止事件mediaRecorder.addEventListener('stop', function () {let bolb = new Blob(chunks, {type: chunks[0].type})let url = URL.createObjectURL(bolb)let video = document.querySelector('video')video.src = url//创建a标签,并调用点击事件let a = document.createElement('a')a.href = urla.download = 'video.webm' //a标签的download属性设置下载文件的文件名a.click() // 调用点击,效果就是鼠标点一下})// 必须手动启动mediaRecorder.start()}btn.click()</script></body></html>
