<!DOCTYPE html> <html> <head> <title>Get Video Frame Example</title> </head> <body> <div id="result"></div> <script> // 获取视频第一帧的函数 function getVideoFirstFrame(videoUrl) { // 创建video元素 const video = document.createElement('video'); video.src = videoUrl; video.setAttribute('crossOrigin', 'Anonymous'); // 处理跨域 video.setAttribute('preload', 'auto'); // auto|metadata|none // 等待视频加载完成 return new Promise((resolve, reject) => { video.addEventListener('loadedmetadata', () => { debugger; // 创建canvas元素 const canvas = document.createElement('canvas'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; // 将视频第一帧绘制到canvas上 const ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, canvas.width, canvas.height); debugger; // 将canvas图像转换为base64格式的数据URI const dataUrl = canvas.toDataURL(); // 返回base64格式的数据URI resolve(dataUrl); }); // 如果视频加载出错,则返回错误信息 video.addEventListener('error', () => { reject(`Failed to load video: ${videoUrl}`); }); }); } // 使用示例 getVideoFirstFrame("https://xxx.com//medias/b20a7c4b68475153194a00f54ed3dbba5.mp4") .then((dataUrl) => { console.log(dataUrl); // 打印获取到的base64格式的数据URI const resultDiv = document.getElementById('result'); resultDiv.innerHTML = `<img src="${dataUrl}" />`; }) .catch((error) => { console.error(error); // 打印错误信息 }); </script> </body> </html>
标签:视频,canvas,const,取该,Base64,video,error,dataUrl From: https://www.cnblogs.com/duhaoran/p/17171238.html