<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>捕获视频帧</title>
<style>
* {
box-sizing: border-box;
}
video,
canvas {
width: 360px;
outline: 1px solid red;
}
img {
width: 100px;
}
.list {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
</style>
</head>
<body>
<div class="list"></div>
<hr />
<script>
init();
async function init() {
const list = document.querySelector('.list');
for (let i = 0; i < 60; i++) {
const frame = await captureFrame(i);
const img = document.createElement('img');
img.src = frame.src;
list.appendChild(img);
}
}
// captureFrame()
function captureFrame(time = 0) {
return new Promise((resolve) => {
const video = document.createElement('video');
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
video.currentTime = time;
video.muted = true;
video.autoplay = true;
video.addEventListener('canplay', () => {
console.log(' => ', video.videoWidth, video.videoHeight);
if (video.videoWidth < video.offsetWidth) {
canvas.width = video.offsetWidth * devicePixelRatio;
canvas.height = video.offsetHeight * devicePixelRatio;
} else {
canvas.width = video.videoWidth * devicePixelRatio;
canvas.height = video.videoHeight * devicePixelRatio;
}
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.toBlob(
(blob) => {
const src = URL.createObjectURL(blob);
resolve({ src, blob });
},
'image/png',
1
);
});
video.src = './frag_bunny.mp4';
});
// document.body.appendChild(video);
// document.body.appendChild(canvas);
}
</script>
</body>
</html>