YouTube動画をAPIで埋め込みした時に上下左右に出る黒帯を消し全画面表示する方法

YouTube動画をAPIで埋め込みした時に上下左右に出る黒帯を消し全画面表示する方法

javascript

// YouTube Player APIの読み込み
var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// プレイヤーを埋め込む場所(IDを指定)
var ytArea = "#hghghg";
// 埋め込むYouTube動画のID
var ytID = "youtubeID"; // https://youtu.be/〇〇〇の〇〇〇

// プレイヤーの埋め込み
function onYouTubeIframeAPIReady() {
  ytPlayer = new YT.Player(ytArea, {
    videoId: ytID,
    playerVars: {
      rel: 0, // 関連動画の非表示
      controls: 0, // プレイヤーコントロールの非表示
      showinfo: 0, // タイトルなどの非表示
      modestbranding: 1, // YouTubeロゴの非表示
      iv_load_policy: 3, // アノテーションの非表示
      wmode: "transparent"
    },
    events: {
      onReady: onPlayerReady,
      onStateChange: onPlayerStateChange
    }
  });
}

// 動画の準備完了後の動作
function onPlayerReady(e) {
  ytPlayer.playVideo();
  ytPlayer.mute();
  ytPlayer.setPlaybackQuality("default"); // 画質(small・medium・large・hd720・hd1080・highres・default)
}

// 動画再生中と再生後の動作
function onPlayerStateChange(e) {
  var ytStatus = e.target.getPlayerState();
  if (ytStatus === YT.PlayerState.PLAYING) {
    //再生中
  }
  if (ytStatus === YT.PlayerState.ENDED) {
    //再生後
    ytPlayer.playVideo();
    ytPlayer.mute();
  }
}

// 上下左右に出てくる黒帯を非表示
var $WIN = $(window); // ブラウザのウインドウを取得する
// var WIN_H;
// var win_W;

function yt_screen_retio() {
  // 上下左右の縦横比を調節する関数
  const WIN_H = $WIN.height(); // windowの高さを取得
  const WIN_W = $WIN.width(); // windowの幅を取得
  const screen_switch = 0.5625; // youtubeの縦横比16:9=>9/16した値
  const screen_ratio = WIN_H / WIN_W; // windowの高さの値/windowの幅の値
  const ratio_H = WIN_H / screen_switch; // windowの高さ/縦横比の値
  const ratio_W = WIN_W * screen_switch; // windowの幅*縦横比の値

  if (screen_ratio > screen_switch) {
    // windowの高さの値/windowの幅の値>youtubeの縦横比16:9=>9/16した値
    $("#player").css({
      height: "100%",
      width: ratio_H,
      "margin-top": "0",
      "margin-left": -ratio_H / 2,
      // "margin-left": -ratio_H,
      left: "50%",
      top: "0"
    });
  } else {
    $("#player").css({
      width: "100%",
      height: ratio_W,
      "margin-top": -ratio_W / 2,
      "margin-left": "0",
      top: "50%",
      left: "0"
    });
  }
}

$WIN.on("resize", function() {
  // windowの縦横比が変わったら実行する処理
  yt_screen_retio();
});

$(function() {
  // domツリーが構築したら実行する処理
  yt_screen_retio();
});

 

参考サイト:
https://teratail.com/questions/172729

 

category cloud