Online Book Reader

Home Category

HTML5 Canvas [98]

By Root 6579 0
codecs="vp8, vorbis"' >

0%

In JavaScript, we need to create the same type of eventWindowLoaded() function that we have created many times previously in this book. This function is called when the HTML page has finished loading. In eventWindowLoaded() we need to create two listeners for two more events that are dispatched from the HTMLVideoElement object:

progress

Dispatched when the video object has updated information about the loading progress of a video. We will use this event to update the percentage text in the loadingStatus

.

canplaythrough

Dispatched when the video has loaded enough that it can play in its entirety. This event will let us know when to start playing the video.

Below is the code that creates the listeners for those events:

function eventWindowLoaded() {

var videoElement = document.getElementById("thevideo");

videoElement.addEventListener('progress',updateLoadingStatus,false);

videoElement.addEventListener('canplaythrough',playVideo,false);

}

The updateLoadingStatus() function is called when the progress event is dispatched from the video element. This function calculates the percent loaded by calculating the ratio of the already-loaded bytes (videoElement.buffered.end(0)) by the total bytes (videoElement.duration), and dividing that value by 100. That value is then displayed by setting the innerHTML property of the loadingStatus

, as shown in Figure 6-5. Remember, this is only for displaying the progress. We still need to do something once the video has loaded.

NOTE

At the time of this writing, Firefox did not support the videobuffered property, but this was planned for Firefox version 4.0.

function updateLoadingStatus() {

var loadingStatus = document.getElementById("loadingStatus");

var videoElement = document.getElementById("thevideo");

var percentLoaded = parseInt(((videoElement.buffered.end(0) /

videoElement.duration) * 100));

document.getElementById("loadingStatus").innerHTML = percentLoaded + '%';

}

Figure 6-5. Preloading a video in JavaScript

The playVideo() function is called when the video object dispatches a canplaythrough event. playVideo() calls the play() function of the video object, and the video starts to play:

function playVideo() {

var videoElement = document.getElementById("thevideo");

videoElement.play();

}

Example 6-5 gives the full code for preloading video.

Example 6-5. Basic HTML5 preloading video

CH6EX5: Basic HTML5 Preloading Video

0%

A Problem with Events and Embedded Video in HTML5


Now that we have gone through this exercise, we have to give you some bad news. While the code we presented for CH6EX5.html works in most HTML5-compliant web browsers,

®Online Book Reader