Reputation: 281
I have made a simple game using canvas, but I can't seem to figure out how to get a quick 3 second intro to play just once within my canvas (before canvas is drawn).
This is what I've got for my html:
<video id="intro" src="https://www.youtube.com/watch?v=tqErAlg-QJU" controls="false" autoplay></video>
<canvas id="myCanvas" width="800" height="400"
style="border:1px solid #000000;">
</canvas>
Upvotes: 1
Views: 3423
Reputation: 42044
My proposal, using your youtube video is:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '400',
width: '800',
videoId: 'tqErAlg-QJU',
events: {
'onReady': function (e) {
e.target.playVideo();
// pause video after 3 seconds
setTimeout(function() {
player.pauseVideo();
}, 3 * 1000);
},
'onStateChange': function (e) {
// if video ended (0) or paused (2)....
if (e.data == 0 || e.data == 2) {
// remove the player
player.destroy();
// toggle the visibility
$('#myCanvas, #player').toggle();
}
}
}
});
}
$(function () {
$('#myCanvas').hide();
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
<div id="player"></div>
<canvas id="myCanvas" width="800" height="400" style="border:1px solid #000000;"></canvas>
Upvotes: 0
Reputation: 467
Here you have an example, just handle the play event so when the video autoplay run, the canvas draw a copy of that video.
document.addEventListener('DOMContentLoaded', function(){
var v = document.getElementById('intro');
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
v.addEventListener('play', function(){
draw(this,context,canvas.width,canvas.height);
},false);
},false);
function draw(v,c,w,h) {
if(v.paused || v.ended) return false;
c.drawImage(v,0,0,w,h);
setTimeout(draw,20,v,c,w,h);
}
#intro{
position:absolute;
visibility:hidden
}
<video id="intro" height="200" src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4" controls="false" autoplay></video>
<canvas id="myCanvas"
style="border:1px solid #000000;">
</canvas>
Upvotes: 2