Search code examples
javascripthtmlvideocanvasyoutube

Draw youtube in html5 canvas


It's a follow-up question to Detect play event in youtube wrapped via MediaElement.js. I tried to detect play or click event in the question but can't do it because of cross-origin issue (maybe). I also found that you draw the youtube clip directly to canvas, it will not be copied (will be blank), like this:

<!DOCTYPE html>
<html>
<head>
  <title>video in canvas</title> 
  <link rel="stylesheet" href="mediaelementplayer.css" />

  <script src="jquery.js"></script>
  <script src="mediaelement-and-player.min.js"></script>

  <script> 
  $(document).ready( function() {
    $('#v').mediaelementplayer();

    var v = $('#v')[0];
    var canvas = $('#c')[0];
    var context = canvas.getContext('2d');

    console.log('play event entered');
    draw(v, context, 640, 360);
  });

  function draw(v, c, w, h) {
    // if(v.paused || v.ended)  return false;
    console.log("draw event entered");
    c.drawImage(v, 0, 0, w, h);
    setTimeout(draw, 20, v, c, w, h);
  }
  </script> 
</head>

<body>
  <video width="640" height="360" id="v" preload="none">
    <source type="video/youtube" src="http://www.youtube.com/watch?v=nOEw9iiopwI"/>
  </video>
  <canvas id="c" width="640" height="360"></canvas> 
</body>
</html>

Anybody knows other more promising approach to draw youtube stream in canvas? Thanks.


Solution

  • You cannot use canvas drawImage to draw <video> or <img> coming from a different domain.

    Maybe you could proxy Youtube streams through your server, but that probably goes against Youtube TOS