屏幕录制需要使用两个谷歌提供的接口:
    MediaDevicesMediaRecorder
    使用屏幕捕获API:https://developer.mozilla.org/zh-CN/docs/Web/API/Screen_Capture_API/Using_Screen_Capture
    代码实现:

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>Document</title>
    8. </head>
    9. <body>
    10. <video class="video" width="600px" controls></video>
    11. <button class="record-btn" onclick="record()">record</button>
    12. <script>
    13. let btn = document.querySelector('.record-btn')
    14. async function record() {
    15. let stream = await navigator.mediaDevices.getDisplayMedia({
    16. video: true
    17. })
    18. // 需要更好的浏览器支持
    19. const mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9") ? "video/webm; codecs=vp9" : "video/webm"
    20. let mediaRecorder = new MediaRecorder(stream, {
    21. mimeType: mime
    22. })
    23. let chunks = []
    24. // 监听数据提供事件
    25. mediaRecorder.addEventListener('dataavailable', function (e) {
    26. console.log(e);
    27. chunks.push(e.data)
    28. })
    29. // 监听停止事件
    30. mediaRecorder.addEventListener('stop', function () {
    31. let bolb = new Blob(chunks, {
    32. type: chunks[0].type
    33. })
    34. let url = URL.createObjectURL(bolb)
    35. let video = document.querySelector('video')
    36. video.src = url
    37. //创建a标签,并调用点击事件
    38. let a = document.createElement('a')
    39. a.href = url
    40. a.download = 'video.webm' //a标签的download属性设置下载文件的文件名
    41. a.click() // 调用点击,效果就是鼠标点一下
    42. })
    43. // 必须手动启动
    44. mediaRecorder.start()
    45. }
    46. btn.click()
    47. </script>
    48. </body>
    49. </html>