Adding Video Element on the Fly and Drawing it to a Canvas Element
Join the DZone community and get the full member experience.Join For Free
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.
Opinions expressed by DZone contributors are their own.