본문 바로가기
Opensource

유튜브 영상을 배경으로 넣고 싶을 때

by 영감은어디에 2024. 5. 1.

아래 오픈소스를 사용하면 된다. 

https://github.com/stamat/youtube-background

 

GitHub - stamat/youtube-background: ESM / jQuery plugin for creating video backgrounds from YouTube, Vimeo or video file links.

ESM / jQuery plugin for creating video backgrounds from YouTube, Vimeo or video file links. - stamat/youtube-background

github.com

사용법 

1. cdn으로 사용할 js파일을 가져온다.

<script type="text/javascript" src="https://unpkg.com/youtube-background/jquery.youtube-background.min.js"></script>

 

2. 스타일 css와 js 코드를 넣는다. 

<style>
//서서히 나타나고 싶을때
	iframe {
		transition: opacity 500ms ease-in-out;
		transition-delay: 250ms;
	}
</style>


 <div data-vbg="유튜브주소"></div>

 <script type="text/javascript">
        jQuery(document).ready(function() {
            jQuery('[data-vbg]').youtube_background();
        });
 </script>
 

실제로 서서히 나타나고, 모바일에서는 낮은 화질로 바꿔 나오게 하기 위해 아래와 같은 소스를 사용하였다. 

jQuery('[data-vbg]').youtube_background({
  videoId: '아이디값입력',
  muted: true,
  repeat: true,
  start: 0,
  playerVars: {
    autoplay: 1,            
    controls: 0,            
    showinfo: 0,            
    modestbranding: 1,      
    rel: 0,                 
    fs: 0,                 
    iv_load_policy: 3,      
    disablekb: 1,           
    playsinline: 1,
    quality: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'small' : 'hd720',
    origin: window.location.origin, 
    enablejsapi: 1      
  },
  youtubeUrl: 'https://www.youtube-nocookie.com',
});

// 페이드인 효과를 위한 CSS를 동적으로 추가
const style = document.createElement('style');
style.textContent = `
  
  .mainYoutube iframe {
    opacity: 0;
    transition: opacity 1s ease-in-out;
  }
  .mainYoutube iframe.loaded {
    opacity: 1;
  }
`;
document.head.appendChild(style);

// iframe이 로드되면 페이드인 효과 적용
const checkYoutubeIframe = setInterval(() => {
  const iframe = document.querySelector('.mainYoutube iframe');
  if (iframe) {
    iframe.onload = function() {
      iframe.parentElement.classList.add('loaded');
    }
    clearInterval(checkYoutubeIframe);
  }
}, 100);