截取视频中的某一刻为封面
JS基于Canvas实现截取视频中的某个时间节点,并生成图片。
截取视频封面
简述:
基于Canvas和Video,截取视频中的某个时间节点中的画面为视频封面。
思路:
1. 创建一个video标签,设置跨域、src等。
2. 给video注册相关事件,在视频加载完成后设置视频的宽和高,或跳转到指定的时间节点。
3. 在当前帧准备完成后,创建一个canvas画布,并设置相关属性,然后向里面加入视频,用toBlod获取blob流。
代码:
/**
* url 视频地址
* w 宽度
* h 高度
* time 时间节点
* */
const getVideoCover = (params: {url: any, w?: string | number, h?: string | number, time?: number}): Promise<Blob | boolean> => {
return new Promise<Blob>((resolve, reject) => {
if (!params.url) {
console.error("缺少URL!!");
reject(false);
return;
}
const video = document.createElement("video")
video.setAttribute("crossOrigin", "anonymous")
video.setAttribute("src", params.url)
video.setAttribute("preload", "auto")
const captureTime = params.time || 0;
video.addEventListener("loadedmetadata", function() {
video.setAttribute("width", params.w || video.videoWidth);
video.setAttribute("height", params.h || video.videoHeight);
video.currentTime = captureTime;
});
video.addEventListener("loadeddata", function () {
const canvas: HTMLCanvasElement = document.createElement("canvas");
const width = video.width;
const height = video.height;
canvas.width = width;
canvas.height = height;
canvas.getContext("2d")!.drawImage(video, 0, 0, width, height)
canvas.toBlob((blob) => resolve(blob as Blob), "image/jpeg")
canvas.toDataURL("image/jpeg")
})
})
};
getVideoCover({
url: targetVideo,
w: 500,
h: 300,
time: 3000
}).then((res) => {
if (typeof res === "boolean") return;
// imgSrc为图片地址
imgSrc.value = URL.createObjectURL(res);
})
