js实现录屏功能

原文连接:https://blog.csdn.net/weiguang102/article/details/123083770?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168258601016800213082578%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=168258601016800213082578&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~sobaiduend~default-1-123083770-null-null.blog_rank_default&utm_term=JavaScript%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E5%BD%95%E5%B1%8F%E5%8A%9F%E8%83%BD&spm=1018.2226.3001.4450

因为需要用到浏览器的一些机制,所以一般情况下只能在localhost和https中使用,http使用需要配置浏览器,

打开 chrome://flags/#unsafely-treat-insecure-origin-as-secure

将该 flag 切换成 enable 状态

输入框中填写需要开启的域名,譬如 http://example.com",多个以逗号分隔。
重启后生效。

完整代码

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>wgchen</title>
    <link rel="shortcut icon" href="#" />
    <meta name="keywords" content="https://wgchen.blog.csdn.net">
    <meta name="keywords" content="技术文章">
    <meta name="keywords" content="博客">
    <meta name="keywords" content="willem">
    <meta name="keywords" content="ycc">
</head>
<body>
 
<video class="video" width="600px" controls></video>
<button class="record-btn">record</button>

<script>

let btn = document.querySelector(".record-btn")

btn.addEventListener("click", async function () {
  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) {
        chunks.push(e.data)
    })

   mediaRecorder.addEventListener('stop', function(){
      let blob = new Blob(chunks, {
          type: chunks[0].type
      })
      let url = URL.createObjectURL(blob)

      let video = document.querySelector("video")
      video.src = url

      let a = document.createElement('a')
      a.href = url
      a.download = 'video.webm'
      a.click()
  })

    // 必须手动启动
    mediaRecorder.start()
})


</script>  

</body>
</html>

 

posted @ 2023-04-27 16:59  从入门到入土  阅读(214)  评论(0编辑  收藏  举报