HTML and CSS Reference
In-Depth Information
Video on the Canvas Examples
In the last section, we learned that the video playing on the canvas and the video em-
bedded with the <video> tag are, in fact, the same video. It took a lot more code to play
the video on the canvas than it did to embed and play the video in JavaScript. So, this
begs the question: why load video onto the canvas at all?
Well, sometimes simply displaying a video and playing it is not enough. You might
want events to occur as the video is playing, or perhaps you want to use transformations
on it, use it in a game, create custom video controls, or animate it and move it on the
The following five examples will show you in very specific detail why the canvas can
be an exciting way to display video.
Using the currentTime Property to Create Video Events
The first way we will use video in conjunction with Canvas is to use the currentTime
property of a playing video to trigger events. Recall that the currentTime property is
updated as the video plays, and it shows the video's elapsed running time.
For our example, we are going to create a dynamic object in JavaScript containing the
following properties:
The elapsed time to trigger the event
A text message to display on the canvas
The x position of the text message
The y position of the text message
First, we will create an array of these objects and place them into a variable named
messages . We will then create four events (messages that will appear) that will take
place at the elapsed currentTime of 0 , 1 , 4 , and 8 seconds:
var messages = new Array();
messages[0] = {time:0,message:"", x:0 ,y:0};
messages[1] = {time:1,message:"This Is Muir Beach!", x:90 ,y:200};
messages[2] = {time:4,message:"Look At Those Waves!", x:240 ,y:240};
messages[3] = {time:8,message:"Look At Those Rocks!", x:100 ,y:100};
To display the messages, we will call a for:next loop inside our drawScreen() function.
Inside the loop, we test each message in the messages array to see whether the current
Time property of the video is greater than the time property of the message. If so, we
know that it is OK to display the message. We then display the message on the canvas
Search WWH ::

Custom Search