js调用摄像头进行录制、截取图片并保存至本地
https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia
代码如下,可自行尝试
<!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>recorderVideo</title>
</head>
<body>
<div id="contentHolder">
<video id="video" width="600px" height="300px" controls></video>
</div>
<button onclick="startRecorder()">开始录屏</button>
<button onclick="stopRecorder()">停止录屏</button>
<button onclick="clipPhoto()">截取图片</button>
</body>
<script>
// src 是播多媒体文件的;srcObject 是实时流
let mediaRecorder; // 视频录制数据
let mediaStreamTrack; // 视频实时流
// 开始录屏
async function startRecorder() {
mediaStreamTrack = await navigator.mediaDevices.getUserMedia({
video: true
})
video.srcObject = mediaStreamTrack;
video.onloadedmetadata = () => video.play();
// 需要更好的浏览器支持
const mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9")
? "video/webm; codecs=vp9"
: "video/webm";
mediaRecorder = new MediaRecorder(mediaStreamTrack, {
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);
// 将video切换成录制的视频
video.srcObject = null;
video.src = url;
video.onloadedmetadata = () => video.play();
// 下载至本地
let a = document.createElement('a');
a.href = url;
a.download = 'video.mp4';
a.click();
})
// 必须手动启动
mediaRecorder.start();
}
// 停止录屏
function stopRecorder() {
mediaStreamTrack.getVideoTracks().forEach((track) => {
track.stop();
});
mediaRecorder.stop();
}
// 截取图片
function clipPhoto() {
let canvas = document.createElement('canvas');
let { width, height } = video;
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, width, height);
// 下载图片、
let a = document.createElement('a');
a.download = "image";
a.href = canvas.toDataURL('image/png');
a.click();
}
</script>
</html>