<style>
span {
cursor: pointer;
}
.playvideo {
position: relative;
height: 500px;
}
video {
width: 800px;
height: 500px;
border: 1px solid #000;
object-fit: fill;
}
canvas {
position: absolute;
width: 800px;
height: 500px;
left: 1px;
top: 1px;
}
.showimg img {
width: 500px;
height: 250px;
}
.showvideo video {
width: 500px;
height: 250px;
}
</style>
<div>
<span onclick="startRecording()">开始录像</span>
<span onclick="stopRecording()">结束录像</span>
<span onclick="photograph()">拍照</span>
</div>
<div style="display:flex">
<div class="playvideo">
<video></video>
<canvas id="canvas" style="display: none"></canvas>
</div>
<div>
<div class="showvideo">
</div>
<div class="showimg"></div>
</div>
</div>
<script>
function findNthIndex (str, searchChar, n) {
let index = -1;
for (let i = 0; i < n; i++) {
index = str.indexOf(searchChar, index + 1);
if (index === -1) {
return -1;
}
}
return index;
}
let mediaRecorder = null;
let recordedChunks = [];
const startRecording = () => {
const options = { mimeType: 'video/webm;codecs=h264' }; //文件格式
mediaRecorder = new MediaRecorder(window.stream, options);
mediaRecorder.ondataavailable = function (e) {
if (e.data.size > 0) {
recordedChunks.push(e.data);
}
};
mediaRecorder.onstop = function (e) {
const blob = new Blob(recordedChunks, { type: 'video/mp4' });
recordedChunks = [];
const url = window.URL.createObjectURL(blob)
//下载
const a = document.createElement('a');
document.body.appendChild(a);
a.style = 'display: none';
a.href = url;
a.download = 'recorded.mp4';
a.click();
window.URL.revokeObjectURL(url);
// const index =findNthIndex(str,"/",3);
// let newurl = str.slice(index, str.length-1)+".mp4";
// console.log(newurl)
//渲染
let showvideo = document.querySelector(".showvideo");
showvideo.innerHTML = "";
const videoElement = document.createElement('video');
videoElement.src = url;
videoElement.preload="preload"
videoElement.controls = true;
showvideo.appendChild(videoElement);
};
mediaRecorder.start();
};
const stopRecording = () => {
console.log("stopRecording")
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
}
};
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(function (stream) {
window.stream = stream;
// 使用视频流初始化一个 video 元素
const video = document.querySelector('video');
video.srcObject = stream;
video.onloadedmetadata = (event) => video.play();
})
.catch(function (err) {
console.log('Error:', err);
});
function photograph () {
let v =
document.querySelector("video");
let canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 600;
canvas
.getContext("2d")
.drawImage(v, 0, 0, canvas.width, canvas.height);
let data = canvas.toDataURL("image/jpeg", 0.8);
let showimg = document.querySelector(".showimg");
showimg.innerHTML = "";
const img = document.createElement('img');
showimg.appendChild(img);
img.src = data;
// console.log(data)
}
</script>