Skip to main content
aldor10080202
Participating Frequently
April 6, 2019
Answered

HTML5 - Insert Video hosted by Vimeo or YouTube

  • April 6, 2019
  • 2 replies
  • 3467 views

Hi everyone,

I'd like to insert a video component hosted by Vimeo or YouTube in my HTML5 canvas.

The video component let me upload a video from a folder on my computer but apparently does not allow to insert a hosted video.

Is there a way to arrange this issue?

Thank you in advance

This topic has been closed for replies.
Correct answer rosebudd10027515

I have done it. The only issue is clicking on the video does take the user to Youtube. The video will be on top by default, and will load a millisecond faster. If you want it to be behind a transparent published Animate object, use z-index.

Just create a player div and position it where you want it to appear.

<div id="player"></div>

tag.src = "https://www.youtube.com/iframe_api";

    var firstScriptTag = document.getElementsByTagName('script')[0];

    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player;

    function onYouTubeIframeAPIReady() {

        player = new YT.Player('player', {

            height: '184',

            width: '300',

            videoId: '**********',

            playerVars: {

                'autoplay': 1,

'modestbranding':1,

                'controls': 1,

'fs': 0,

'rel': 0

            },

            events: {

                'onReady': onPlayerReady,

                    'onStateChange': onPlayerStateChange

            }

        });

    }

    var playerReady = false;

    function onPlayerReady(event) {

        playerReady = true;

player.mute();

    }

    function onPlayerStateChange(event) {

        if (event.data == YT.PlayerState.ENDED) {

            <!-- alert('done'); -->

        }

    }

2 replies

rosebudd10027515Correct answer
Inspiring
April 8, 2019

I have done it. The only issue is clicking on the video does take the user to Youtube. The video will be on top by default, and will load a millisecond faster. If you want it to be behind a transparent published Animate object, use z-index.

Just create a player div and position it where you want it to appear.

<div id="player"></div>

tag.src = "https://www.youtube.com/iframe_api";

    var firstScriptTag = document.getElementsByTagName('script')[0];

    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player;

    function onYouTubeIframeAPIReady() {

        player = new YT.Player('player', {

            height: '184',

            width: '300',

            videoId: '**********',

            playerVars: {

                'autoplay': 1,

'modestbranding':1,

                'controls': 1,

'fs': 0,

'rel': 0

            },

            events: {

                'onReady': onPlayerReady,

                    'onStateChange': onPlayerStateChange

            }

        });

    }

    var playerReady = false;

    function onPlayerReady(event) {

        playerReady = true;

player.mute();

    }

    function onPlayerStateChange(event) {

        if (event.data == YT.PlayerState.ENDED) {

            <!-- alert('done'); -->

        }

    }

April 12, 2019

You will need to have an explicit player configured to accommodate your video since your video is from a website that doesn't let you access to actual video files

JoãoCésar17023019
Community Expert
Community Expert
April 8, 2019

Hi.

As far as I can tell it's not possible to embed YouTube videos using the video components.

But don't worry because you can use any method available to embed YouTube videos like it's done in regular websites.

Create an iframe with only javascript - Stack Overflow

HTML YouTube Videos

YouTube Player API Reference for iframe Embeds  |  YouTube IFrame Player API  |  Google Developers

Regards,

JC

SorinN
Participant
March 20, 2021

...it is possible using a php function which can extract your html5 <video> source.
Then you can play that source on <video>.

Here is some code which extract the video source for the <video> element and then project this video element (hidden in by css display: none) into a <canvas> element. So you can play the Youtube video on canvas (some basic video controls for <canvas> added).

Save the following code on a PHP file then test on your server.

<?php
$vid = 'fCabZdoD0OI'; //your Youtube video ID like ... 'dgKSqz3it50';

parse_str(file_get_contents("https://youtube.com/get_video_info?video_id=" . $vid), $info);

$playabilityJson = json_decode($info['player_response']);

$title = '&title=' . $playabilityJson->videoDetails->title;

$formats = $playabilityJson->streamingData->formats;

$IsPlayable = $playabilityJson->playabilityStatus->status;

if (strtolower($IsPlayable) != 'ok')
{
  $log = date("c") . " " . $info['player_response'] . "\n";
  file_put_contents('./video.log', $log, FILE_APPEND);
}

$result = array();

//$theLink = '';

if (!empty($info) && $info['status'] == 'ok' && strtolower($IsPlayable) == 'ok')
{
  $i = 0;

  foreach ($formats as $stream)
  {
    $streamUrl = $stream->url;
    $type = explode(";", $stream->mimeType);
    $qualityLabel = '';

    if (!empty($stream->qualityLabel))
    {
      $qualityLabel = $stream->qualityLabel;
    }

    $videoOptionsOrg[$i]['link'] = $streamUrl;
    $videoOptionsOrg[$i]['type'] = $type[0];
    $videoOptionsOrg[$i]['quality'] = $qualityLabel;

    if ($videoOptionsOrg[$i]['quality']  == 360) // you can search for 720 or 1080 ...
    {
      $type = '&' . $videoOptionsOrg[$i]['type'];
      $theLink = urldecode($videoOptionsOrg[$i]['link'] . $title . $type);
    }
    $i++;
  }

  $result['videos'] = array(
    'info' => $info,
    'formats' => $videoOptionsOrg
  );

  //print_r($result);
  //echo $theLink;
}
?>

<video id="video" controls width="600" height="340" style="display: none;" data-info="you can change display: none to display: block;">
  <source src="<?= $theLink ?>">
</video>
<h3>Clicking on Canvas you can play stop the video.<br>
  Clicking / Dragging over progress bar HTML5 element you can set the video Current Time</h3>
<canvas id="canva" width="600" height="340"></canvas>
<progress id="progress" style="display: block; border: none; height: 34px;" value="0" max=""> 0% </progress>
<p id="info">INFO</p>

<script>
  var video = document.getElementById('video');
  var canvas = document.getElementById('canva');
  var ctx = canvas.getContext('2d');
  var info = document.getElementById('info');
  var progress = document.getElementById('progress');

  progress.style.width = canvas.clientWidth + 'px';

  var playstate = 'pause';
  var W, H, T, D, P, newtime, max, pos, oldplaystate;

  (function() {

    video.onloadedmetadata = function() {
      D = video.duration;
      max = progress.clientWidth;
      progress.setAttribute("max", D);
    }

    video.addEventListener('play', function() {
      var $this = this;
      progress.setAttribute("max", D);

      (function loop() {
        if (!$this.paused && !$this.ended) {
          T = video.currentTime;
          test();
          info.innerHTML = 'duration : ' + D + ' || current T : ' + T;
          progress.setAttribute("value", T);
          window.requestAnimationFrame(loop);
        }
      })();
    });

    video.addEventListener('canplay', function() {
      test();
    });

    canvas.addEventListener('mouseup', function() {
      cvPlay();
    });

  })();

  function test() {
    ctx.drawImage(video, 0, 0);
  }

  progress.onmouseup = function() {

    info.innerHTML = newtime;
    progress.setAttribute("value", newtime);
    video.currentTime = newtime;

    if (oldplaystate === 'play') {
      playstate = 'play';
      video.play();
      oldplaystate = playstate;
    } else {
      playstate = 'pause';
      oldplaystate = playstate;
      video.pause();
    }
    this.onmousemove = function() {}
  }

  progress.addEventListener('mousedown', function(e) {

    if (playstate === 'play') {
      oldplaystate = 'play';
    }

    playstate = 'pause';
    video.pause();

    if (newtime > D) {
      newtime = D;
    }

    calc(e);

    this.onmousemove = function(e) {
      calc(e);
    }

    info.innerHTML = newtime + 'draginnn...';

  }, true);

  function cvPlay() {
    if (playstate == 'pause' || playstate == '') {
      oldplaystate = playstate = 'play';
      video.play();
    } else {
      oldplaystate = playstate = 'pause';
      video.pause();
    }
    console.log(oldplaystate + ' - ' + playstate);
  }

  function calc(evt) {
    pos = evt.pageX - (progress.offsetLeft);
    newtime = pos / max * D;
    progress.value = newtime;
  }
</script>