JS取视频第一帧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="file" id="file" />
</body>
</html>
<script>
function imageScale(width, originWidth, originHeight) {
const scaleRatio = width / originWidth;
const scaleHeight = scaleRatio * originHeight;
return [width, scaleHeight];
}
function getVideoPoster(file, scaleWidth, quality = 0.5) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (e) => {
let video = document.createElement("video");
video.src = e.target.result;
video.onloadeddata = () => {
const canvas = document.createElement("canvas");
const [width, height] = imageScale(
scaleWidth,
video.videoWidth,
video.videoHeight
);
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.fillRect(0, 0, width, height);
ctx.drawImage(video, 0, 0, width, height);
ctx.imageSmoothingEnabled = false;
canvas.toBlob(
async (blob) => {
video.pause();
video = null;
resolve(blob);
},
"image/jpeg",
0.5
);
};
video.onerror = () => {
video.pause();
video = null;
reject();
};
video.muted = false;
video.play();
};
});
}
file.onchange = function () {
getVideoPoster(this.files[0], 200).then((blob) => {
let url = window.URL.createObjectURL(blob);
const img = document.createElement("img");
img.src = url;
img.width = 200;
document.body.appendChild(img);
});
}
</script>