HTML and CSS Reference
In-Depth Information
<!DOCTYPE html>
<head>
<title>Grayscale a Video</title>
<meta charset="utf-8" />
<script>
window.onload=function() {
document.getElementById("videoobj").
addEventListener("timeupdate", drawVideo, false);
}
function drawVideo() {
var videoObj = document.getElementById("videoobj");
var canvasObj = document.getElementById("canvasobj");
var ctx = canvasObj.getContext("2d");
ctx.drawImage(videoObj,0,0);
}
</script>
</head>
<body>
<video id="videoobj" controls width="480" height="270">
<source src="videofile.mp4" type="video/mp4" />
<source src="videofile.webm" type="video/webm" />
</video>
<canvas id="canvasobj" width="480" height="270"></canvas>
</body>
The application works in IE10, Firefox, Opera, and WebKit Nightly, but not Chrome (not even
Canary), or Safari 5. However, in the browsers where the application worked, the drawing ac-
tion in the canvas element was choppy, and lagged noticeably behind the video, as shown in
Opera in Figure 4-1 .
One of the problems with timeupdate is that it didn't fire quickly enough. Searching about
through online documentation, I found that Firefox fires the timeupdate event every 250 mil-
liseconds, and I am assuming the other browsers do something similar. Untold frames have
flipped past in such a long time!
Though timeupdate was sufficient for our playback indicator, it isn't sufficient for video
playback. A better approach, and one that was taken in the HTML5 Doctor article, is to use the
JavaScript function setTimeout , and a time frame of 20 milliseconds—over ten times faster
than using timeupdate .
The script block in Example 4-1 is modified to now use setTimeout , as shown in
Example 4-2 . Since we're no longer using an event that's playback-related, we also have to
know when to stop drawing. The code tests to ensure that the video isn't paused or finished,
first, before doing the draw.
Search WWH ::




Custom Search