Canvas How to - Wait for a video to load








Question

We would like to know how to wait for a video to load.

Answer


<!--from ww w  .  j  a  va2s.com-->

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
var vid, ctx;
function play() {
    console.log("play");
    vid.play();
    setInterval(function() {
        ctx.drawImage(vid, 0, 0);
    }, 60);
}
function init() {
    var can = document.getElementById('canvas1');
    ctx = can.getContext('2d');
    vid = document.createElement('video');
    vid.src = "http://upload.wikimedia.org/wikipedia/commons/8/8c/Anthropoides_paradisea1.ogg";
    vid.autoplay = false;
    vid.loop = true;
    vid.addEventListener("canplaythrough", play, false);
}
//]]>  
</script>
</head>
<body onLoad="init();">
  <canvas id="canvas1" width="500" height="500"></canvas>
</body>
</html>

The code above is rendered as follows: