One of the requirements in a project that I work on lately is to create on the fly video elements and to show them inside a canvas element. This post will show you how you can do it.
Adding Video Element on the Fly
The HTML5 Video element is a DOM element. As any other DOM element you can create it using the document.createElement function and then to supply its relevant properties. After the creation of the element you will have to append it into the DOM tree. One place that you might append the element to is at the end of the body element (but you might append it to other elements as well). The following code snippet shows how to create a video element on the fly and append it to the body element:
Drawing The Video to a Canvas Element
After you have created the video element and append it to the DOM tree the video won’t start up until somebody will play it (or you use the autoplay attribute). If you need to display that video on a canvas you will have to wire up an event handler to the video’s onplay function and to draw the video on the canvas in the handler. Pay attention that you will have to draw the video’s frames or the canvas will only show the first frame that you draw. This is way you will need to call the draw in an interval. Here is a simple example of how to do exactly that:
The Full Example
Here is the full example:
When you need to create on the fly videos in your web pages you can just create them as a any other DOM element. If you need to show these elements inside a canvas then you will have to draw the video inside the canvas element while it is playing.