
返回文章
ARTICLE
上传视频生成视频封面图展示
从上传视频生成封面 用浏览器的 <video 解码本地文件,再把目标时刻画到 Canvas。先等元数据和首帧可用,跳转时间后等 seeked,最后导出图片。原示例的 drawImage 缺逗号、loaddeddata 拼写错误已修正。 下面是独立的 JavaScript 实现,不依赖上传组件;放在浏览器模块里调用即可。
从上传视频生成封面
用浏览器的 <video> 解码本地文件,再把目标时刻画到 Canvas。先等元数据和首帧可用,跳转时间后等 seeked,最后导出图片。原示例的 drawImage 缺逗号、loaddeddata 拼写错误已修正。
下面是独立的 JavaScript 实现,不依赖上传组件;放在浏览器模块里调用即可。目标格式为 PNG,输入时间以秒计。
async function videoCover(file, requestedTime = 0) {
if (!Number.isFinite(requestedTime) || requestedTime < 0) {
throw new Error('截帧时间必须是非负有限数');
}
const video = document.createElement('video');
const url = URL.createObjectURL(file);
video.muted = true;
video.playsInline = true;
video.preload = 'auto';
function waitFor(event, start) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => finish(new Error('视频解码超时')), 15000);
function finish(error) {
clearTimeout(timer);
video.removeEventListener(event, onReady);
video.removeEventListener('error', onError);
error ? reject(error) : resolve();
}
function onReady() { finish(); }
function onError() { finish(new Error('当前浏览器无法解码此视频')); }
video.addEventListener(event, onReady, { once: true });
video.addEventListener('error', onError, { once: true });
try { start(); } catch (error) { finish(error); }
});
}
try {
await waitFor('loadeddata', () => { video.src = url; video.load(); });
if (!video.videoWidth || !video.videoHeight || !Number.isFinite(video.duration)) {
throw new Error('视频尺寸或时长无效');
}
if (requestedTime >= video.duration && requestedTime !== 0) {
throw new Error('截帧时间必须小于视频时长');
}
if (requestedTime !== video.currentTime) {
await waitFor('seeked', () => { video.currentTime = requestedTime; });
}
const canvas = document.createElement('canvas');
const scale = Math.min(1, 1280 / video.videoWidth);
canvas.width = Math.max(1, Math.round(video.videoWidth * scale));
canvas.height = Math.max(1, Math.round(video.videoHeight * scale));
const context = canvas.getContext('2d');
if (!context) throw new Error('Canvas 2D 不可用');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
return await new Promise((resolve, reject) => {
canvas.toBlob((blob) => blob ? resolve(blob) : reject(new Error('图片导出失败')), 'image/png');
});
} finally {
video.pause();
video.removeAttribute('src');
video.load();
URL.revokeObjectURL(url);
}
}
接入上传表单
<input id="video-file" type="file" accept="video/*">
<img id="video-preview" alt="视频封面预览">
<script type="module">
// 将上面的 videoCover 函数放在这里,或从模块导入。
let previewUrl;
document.querySelector('#video-file').addEventListener('change', async (event) => {
const file = event.target.files[0];
if (!file) return;
try {
const blob = await videoCover(file, 0);
if (previewUrl) URL.revokeObjectURL(previewUrl);
previewUrl = URL.createObjectURL(blob);
document.querySelector('#video-preview').src = previewUrl;
// 需要上传时:const data = new FormData(); data.append('cover', blob, 'cover.png');
} catch (error) {
console.error(error);
}
});
window.addEventListener('pagehide', () => {
if (previewUrl) URL.revokeObjectURL(previewUrl);
});
</script>
视频对象 URL 在截帧完成或失败后释放;预览图片的对象 URL 应在更换预览或离开页面时释放,不能赋给图片后立刻撤销。文件扩展名和 accept 不能保证解码成功,仍需错误与超时处理。远程视频还需要先设置 crossOrigin,且资源服务端允许跨域,否则 Canvas 导出会失败。本例只处理本地 File。
参考:loadeddata、seeked、toBlob。2026-11-11 修订。