录屏功能
HTML代码
<!DOCTYPE html>
<html>
<head>
<title>视频录制</title>
<meta charset="UTF-8" />
<style>
.btn {
display: inline-block;
line-height: 1;
white-space: nowrap;
background: #fff;
border: 1px solid #dcdfe6;
text-align: center;
box-sizing: border-box;
outline: none;
margin: 0;
font-weight: 500;
padding: 12px 20px;
color: #fff;
}
.record-btn {
background-color: #409eff;
border-color: #409eff;
}
</style>
</head>
<body>
<video class="video" width="600px" controls></video>
<button class="record-btn btn">开始录屏</button>
</body>
</html>
JS代码
<script>
let btn = document.querySelector(".record-btn")
btn.addEventListener("click",function () {
navigator.mediaDevices.getDisplayMedia({video: true}).then((stream) =>{
const mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9") ? "video/webm; codecs=vp9" : "video/webm"
let mediaRecorder = new MediaRecorder(stream, {
mimeType: mime
})
let videoArr = []
mediaRecorder.addEventListener('dataavailable', function (e) {
videoArr.push(e.data)
})
mediaRecorder.addEventListener('stop', function () {
let blob = new Blob(videoArr, {
type: videoArr[0].type
})
let url = URL.createObjectURL(blob)
let video = document.querySelector("video")
video.src = url
})
mediaRecorder.start()
},() => {
alert("取消录屏");
})
})
</script>
全部代码
<!DOCTYPE html>
<html>
<head>
<title>视频录制</title>
<meta charset="UTF-8" />
<style>
.btn {
display: inline-block;
line-height: 1;
white-space: nowrap;
background: #fff;
border: 1px solid #dcdfe6;
text-align: center;
box-sizing: border-box;
outline: none;
margin: 0;
font-weight: 500;
padding: 12px 20px;
color: #fff;
}
.record-btn {
background-color: #409eff;
border-color: #409eff;
}
</style>
</head>
<body>
<video class="video" width="600px" controls></video>
<button class="record-btn btn">开始录屏</button>
<script>
let btn = document.querySelector(".record-btn")
btn.addEventListener("click",function () {
navigator.mediaDevices.getDisplayMedia({video: true}).then((stream) =>{
const mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9") ? "video/webm; codecs=vp9" : "video/webm"
let mediaRecorder = new MediaRecorder(stream, {
mimeType: mime
})
let videoArr = []
mediaRecorder.addEventListener('dataavailable', function (e) {
videoArr.push(e.data)
})
mediaRecorder.addEventListener('stop', function () {
let blob = new Blob(videoArr, {
type: videoArr[0].type
})
let url = URL.createObjectURL(blob)
let video = document.querySelector("video")
video.src = url
})
mediaRecorder.start()
},() => {
alert("取消录屏");
})
})
</script>
</body>
</html>