星期一 , 14 4 月 2025

提取第二帧作为视频封面

document.addEventListener('DOMContentLoaded', function() {
  const videos = document.querySelectorAll('video');
  
  videos.forEach(video => {
    // Create a temporary canvas to capture the frame
    const canvas = document.createElement('canvas');
    
    // Function to capture the second frame
    const captureSecondFrame = () => {
      // Set the current time to a small value to get to the second frame
      // The exact time may vary based on your video's frame rate
      // For a typical 30fps video, the second frame would be around 0.033 seconds
      video.currentTime = 0.033;
      
      // Now we need to wait for the seek to complete
      video.addEventListener('seeked', function onSeeked() {
        // Now we're at the second frame, capture it
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
        
        // Use the canvas as poster
        const poster = canvas.toDataURL('image/jpeg');
        video.setAttribute('poster', poster);
        
        // Reset preload attribute to original value
        video.preload = 'none';
        
        // Remove the event listeners
        video.removeEventListener('seeked', onSeeked);
        video.removeEventListener('loadeddata', captureSecondFrame);
        
        // Pause the video
        video.pause();
        
        // Reset the current time
        video.currentTime = 0;
      }, { once: true });
    };
    
    // Store original preload value
    const originalPreload = video.preload;
    
    // Temporarily change preload to load video data
    video.preload = 'auto';
    
    // When video data is loaded, capture the second frame
    video.addEventListener('loadeddata', captureSecondFrame);
    
    // Start loading the video
    video.load();
  });
});