HTML and CSS Reference
In-Depth Information
Displaying a Video on HTML5 Canvas
First, we must learn the basics of displaying video on HTML5 Canvas. There are a few im-
portant things to note that are not immediately obvious when you start working with video
and the canvas. We worked through them so that you don't have to do it yourself.
Video must still be embedded in HTML
Even though the video is displayed only on HTML5 Canvas, you still need a <video> tag in
HTML. The key is to put the video in a <div> (or a similar construct) and to set the display
CSS style property of that <div> to none in HTML. This will ensure that while the video is
loaded in the page, it is not displayed. If we wrote the code in HTML, it might look like this:
<div style= "position: absolute; top: 50px; left: 600px; display:none" >
<video loop controls id= "thevideo" width= "320" height= "240" preload= "auto" >
<source src= "muirbeach.webm" type= 'video/webm; codecs="vp8, vorbis"' >
<source src= "muirbeach.mp4" type= 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
<source src= "muirbeach.ogg" type= 'video/ogg; codecs="theora, vorbis"' >
However, we already know that we don't want to use an HTML embed. As we stated at the
end of the last section, video events do not appear to fire reliably when video elements are
embedded in the HTML page. For this reason, we need a new strategy to load video dynam-
ically—we'll create the <div> and <video> elements in JavaScript.
The first thing we do in our JavaScript is add a couple variables to hold references to the dy-
namic HTML elements we will create. The videoElement variable will hold the dynamically
created <video> tag, while videoDiv will hold the dynamically created <div> :
var videoElement ;
var videoDiv ;
We use this method to create global variables throughout this chapter. There are many reasons not
to use global variables, but for these simple applications, it's the quickest way to get something on
the canvas. If you want to learn a better way to handle loading assets, the last section of Chapter 7
employs a strategy to preload assets without the use of global variables.
Next, we create our dynamic form elements in the eventWindowLoaded() function. First, we
use the createElement() method of the document DOM object to create a <video> element
and a <div> element, placing references to them in the variables we just created:
Search WWH ::

Custom Search