У меня есть код, который показывает видео на мобильном телефоне. Он просто показывает кнопку воспроизведения без видео за ней. Когда я нажимаю кнопку воспроизведения, видео запускается нормально, но мне нужно, чтобы за ним что-то стояло.
Вот как это выглядит:
<div class = "flex justify-center sm:mt-[-200px] z-10 relative lg:flex-row pb-12 xl:pb-12 flex-col-reverse items-center bg-gradient-to-l from-yellow-50 to-yellow-100 rounded-xl">
<div class = "video-container mt-14 rounded-lg overflow-hidden w-full max-w-[800px]">
<!-- Heading before the video -->
<div class = "text-center text-4xl font-bold mb-10">
Learn about
</div>
<!-- Video container -->
<div class = "w-[90%] mx-auto">
<!-- Encapsulate video within a div for better control -->
<video class = "w-full h-auto rounded-lg>
<source src = " {{ url_for( 'static', filename='home.mp4' ) }} " type = "video/mp4 ">
Your browser does not support the video tag.
</video>
</div>
</div>
</div>
Чтобы обеспечить эффективную загрузку видео, вы можете применить preload = "metadata"
к тегу видео и указать вторую часть первого кадра #t=0.1
в источнике видео:
<video preload = "metadata">
<source src = "https://example.com/foo.mp4#t=0.1" type = "video/mp4">
Your browser does not support the video tag.
</video>
Если это решение вам не подходит, вы можете альтернативно захватить первый кадр с помощью JavaScript:
async function captureThumbnailVideo(videoURL) {
const video = document.createElement('video');
video.crossOrigin = 'anonymous';
video.src = videoURL;
video.autoplay = true;
video.preload = 'metadata';
// Load video in Safari / IE11
video.muted = true;
video.playsInline = true;
const canvas = document.createElement('canvas');
let thumbnail = '';
try {
await video.play();
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const context = canvas.getContext('2d');
context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
const thumbnailBlob = (await new Promise((resolve) =>
canvas.toBlob(resolve, 'image/jpeg')
)) as Blob;
thumbnail = URL.createObjectURL(thumbnailBlob);
} catch (e) {
await new Promise<void>((resolve) => {
video.onloadedmetadata = () => {
video.currentTime = 1; //? seek to 1 second to ensure enough video data for capture
video.onseeked = () => {
const context = canvas.getContext('2d');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight); //? draw the video frame to canvas
video.pause();
resolve();
};
};
});
thumbnail = canvas.toDataURL('image/png');
}
const duration = video.duration;
// Destroy the video once we are done with it.
video.pause(); // pause the video before removing it
video.src = ''; // empty the video source to release any resources associated with it
video.load(); // force the browser to release resources used by the video element
video.remove();
// Destroy the canvas once we are done with it.
canvas.remove();
return { thumbnail, duration };
}
const thumnail = await captureThumbnailVideo(url).then(({ thumbnail }) => {
document.querySelector('video').setAttribute('poster', thumbnail)
})
Если у вас уже есть собственный значок, вы можете просто добавить атрибут «постер» к тегу видео:
<video poster = "/example.jpg">
Используйте атрибуты autoplay
, loop
, muted
в теге <video>
.
<video class = "w-full h-auto rounded-lg autoplay loop muted>
<source src = "{{ url_for('static', filename='home.mp4') }}" type = "video/mp4">
Your browser does not support the video tag.
</video>
autoplay
- Автоматически воспроизведет видео.loop
- видео никогда не закончится, оно будет идти по кругуmuted
— видео будет воспроизводиться без звука (лучше всего для фона)
Вы можете добавить изображение постера в тег видео, чтобы оно отображалось перед началом видео,
<video poster = "/images/example.jpg">