Explain Codes LogoExplain Codes Logo

How to set the thumbnail image on HTML5 video?

html
responsive-design
lazy-loading
meta-tags
Anton ShumikhinbyAnton Shumikhin·Oct 26, 2024
TLDR

Specify a video thumbnail using the poster attribute in the <video> tag. Just provide the URL of your image. Here's a quick-start snippet:

<video controls poster="thumbnail.jpg"> <source src="video.mp4" type="video/mp4"> </video>

Replace "thumbnail.jpg" and "video.mp4" with your image and video paths, respectively.

Thumbnail like a boss: the essential guide

Squeezing the first frame as a fallback thumbnail

What if you don't have a separate image for a thumbnail? No worries, we've got your back. Grab the first frame of the video by adding #t=0.1 at the end of video URL.

<video controls> <source src="video.mp4#t=0.1" type="video/mp4"> </video>

(Don't tell anyone it's a fallback 🤫)

Lazy loading and responsive design: win-win

Pitch-perfect design that'll look great on any device and lazy loading to give page load times a boost.

<video controls poster="thumbnail.jpg" style="max-width:100%; height:auto;" loading="lazy"> <source src="video.mp4" type="video/mp4"> </video>

Now that's what I call a lazy gold medalist in the Responsive Olympics 🥇.

SEO game on point

To index or not to index, that's the question. But HTML meta tags are always the answer. Add relevant meta tags to make your videos more discoverable.

JavaScript magic: Dynamic at its finest

Abra-ca-capture (get it?)

With a flick of JavaScript wand, capture a thumbnail at a blink of an eye. Here's how to set the thumbnail at a certain point in the video:

var video = document.querySelector('video'); video.addEventListener('canplay', function() { this.currentTime = magicalPointInVideo; }); video.addEventListener('seeked', function() { // Capture your desired thumbnail using canvas });

It's abracadabra, but for developers.

Artistic flair with canvas

Blend <canvas> with a sprinkle of XMLHttpRequest and base64 encoding. And voila, you've pulled images straight out of the video and transported them to the server like a magician.

No browser left behind: spreading compatibility

Different browsers, different needs. Specify source types like mp4, ogg, and webm and cover all your bases.

Creating petite & pretty video controls

Use SVG icons for your video controls for a crystal-clear look while being light as a feather.

Cater to the user: Autoplay & controls

Autoplay gets the video rolling. Controls make it a smooth ride. Don't forget the controls attribute in your <video> tag.

Oh server of mine: PHP sidestepping

Got some PHP skills? Use them for saving and retrieving video thumbnails from the server. Matt damon would've loved some PHP power while saving private Ryan, wouldn't he?