HTML and CSS Reference
In-Depth Information
Using the currentTime Property to Create Video Events
The first way we will use video in conjunction with Canvas is to use the
currentTime
prop-
erty 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.
Forourexample, wearegoingtocreate adynamicobjectinJavaScript containing thefollow-
ing properties:
time
time
The elapsed time to trigger the event
message
A text message to display on the canvas
x
The
x
position of the text message
y
The
y
position of the text message
First,wewill create anarrayofthese objects andplace themintoavariable 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
var
messages
=
new
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. In-
side the loop, we test each message in the
messages
array to see whether the
currentTime
propertyofthevideoisgreaterthanthe
time
propertyofthemessage.Ifso,weknowthatitis
OK to display the message. We then display the message on the canvas using the
fillStyle
ure 6-8
:
for
for
(
var
var
i
=
0
;
i
<
messages
.
length
;
i
++
) {
var
var
tempMessage
=
messages
[
i
];
iif
(
videoElement
.
currentTime
>
tempMessage
.
time
) {