601try {602const canvas = document.createElement('canvas');603canvas.width = video.videoWidth || video.clientWidth;604canvas.height = video.videoHeight || video.clientHeight;605const ctx = canvas.getContext('2d');606ctx.drawImage(video, 0, 0, canvas.width, canvas.height);607resolve(canvas.toDataURL('image/jpeg', 0.8));608} catch (err) {609reject(err);610}611};612
if (video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) { getFrameAsImage(); } else { video.addEventListener('loadeddata', getFrameAsImage, { once: true }); } });}/** * @param {HTMLVideoElement} video */function t396_video__lazyLoadProcessHTMLVideo__handleAutoplayError(video, error) { /** * Ошибка NotAllowedError возникает в тех случаях, когда браузер блокирует автовоспроизведение видео без действия от пользователя. * Проблема может возникнут по разным причинам, но основной посыл – в текущем окружении воспроизведение невозможно. * * В этом случае рекомендуется выводить явный интерфейс для управления состоянием видео. В этом случае воспроизведение происходит корректно. * * https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Autoplay#the_play_method */ if (error.name === 'NotAllowedError') { if (video.parentElement.querySelector('.tn-manual-play-button')) { return; } const button = document.createElement('button'); button.classList.add('tn-manual-play-button'); button.style.fontSize = '40px'; button.style.color = '#fff'; button.style.position = 'absolute'; button.style.inset = '0'; button.style.border = 'none'; button.style.display = 'flex'; button.style.alignItems = 'center'; button.style.justifyContent = 'center'; button.style.cursor = 'pointer'; button.style.zIndex = '1'; // Создаем превью из первого кадра видео t396_video__captureVideoFrame(video) .then(previewUrl => { button.style.backgroundImage = `url(${previewUrl})`; button.style.backgroundSize = 'cover'; button.style.backgroundPosition = 'center'; }) .catch(err => { // Если не удалось создать превью (CORS или другие ошибки), используем черный фон console.warn('Could not generate video preview:', err.message); button.style.background = '#000'; }); const reInitializeVideo = () => { video .play() .catch(error => { console.error('Could not manually initialize HTML video with autoplay:', error); }) .finally(() => { button.remove(); }); }; button.addEventListener('click', reInitializeVideo, { once: true }); video.parentElement.append(button); } console.error('Error trying to lazyload video with autoplay:', error);}/** * Добавление логики прелоиданга для HTML-видео * Если видео не имеет обложки, то показываем спиннер, пока видео не загрузится * Иначе обложка сама в каком-то смысле выступает в роли лоадера * * @param {HTMLDivElement} atom - обертка над видео с классом .tn-atom * @param {HTMLVideoElement} video - видео * @param {Boolean} isCoverFit - флаг, для цвета бэкграунда * @param {Boolean} hasCover - есть ли у видео обложка */function t396_video__setLoadingStateForHTMLVideo(atom, video, isCoverFit, hasCover) { if (!video) return; const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent) || ('ontouchend' in document && /Macintosh/.test(navigator.userAgent)); if (!hasCover) { atom.style.backgroundImage = 'url("https://tilda.ws/img/spinner-white.gif")';