- Chapter 9: Using Video with Canvas
- The Canvas Element
- The 2D API
- Taking a Screen Shot of an HTML5 Video
- Making a Copy of a Playing Video
- Playing the Video Copy in Greyscale
- Wrapping Up
Making a Copy of a Playing Video
In the previous example, you saw how easy it was to take screen shots of a video as it’s playing. But what if you wanted to take that a bit further and update the copied image automatically as the main video is playing, in effect, creating an exact copy of the video, but smaller? All you need to do is use the same code from the preceding example and add listeners for various events that update the image in the canvas element.
Recall from Chapter 5 the events that are raised when a video is playing, paused, stopped, or ended. It is these events, more specifically the play, paused, and ended events, that you need to use.
To achieve the video copy, you need to use the standard setInterval() function, which allows you to specify that a particular JavaScript function is to be called at specific intervals. When the video starts to play, you listen and catch the play event, and using the setInterval() function, set the snap() function you defined earlier to be called every 33 milliseconds:
video.addEventListener(‘play’, function() { setInterval(“snap()”, 33); }, false);
This code causes the snap() function to automatically update the canvas’s drawing context with a new screen shot of the video, which makes it look like it’s actually playing (Figure 9.3).
Figure 9.3 The canvas element on the right updates automatically as the video is playing, keeping it in sync with the video (A and B).
You also should listen for when the video has been paused or ended (using the paused and ended events) so that you can stop the snap() function from being called at the intervals defined. To clear an interval, you call the standard JavaScript function clearInterval():
video.addEventListener(‘paused’, function() { clearInterval(); }, false); video.addEventListener(‘ended’, function() { clearInterval(); }, false);
And that’s all there is to it. When you play the video, it will update the image in the canvas as it’s playing, even if you skip ahead (Figure 9.4). And when you pause it or end it, the canvas image will stop being updated.
Figure 9.4 The video stays in sync (A) even when you use the seek control to jump ahead in the video (B).
In a similar vein, but slightly more complicated, you’ll next make the video copy appear in greyscale, unlike the colour original. To do this, you need to manipulate the actual pixels of the video, which once again is not as complicated as it might sound.