Example 2: Put Video on the Canvas and Take a Screenshot

Next, we are going to modify the sixth example from this chapter (CH6EX6.html). As a refresher, in that example, we used the Canvas to display a video by dynamically adding an HTMLVideoElement object to the page and then using it as the source for video displayed on the Canvas. For this example, we will use getUserMedia() as the source for the video on the canvas and display it in the same way. However, we will add the ability to take a screenshot of the video by using the canvas context.toDataURL() method.

The first thing we do is create a dynamic video element (videoElement) and a dynamically created <div> to hold it on the page, and then we make both invisible by setting the style of videoDiv to display:none. This will get our video onto the page but hide it, because we want to display it on the canvas.

Next we check our userMediaSupported() function to see whether we can access the webcam. If so, we call startVideo() to start the media capture and then call canvasApp() to start our application:

function eventWindowLoaded() {

    videoElement = document.createElement("video");
    videoDiv = document.createElement('div');
    document.body.appendChild(videoDiv);
    videoDiv.appendChild(videoElement);
    videoDiv.setAttribute("style", "display:none;");
    if (userMediaSupported()) {
        startVideo();
        canvasApp();
    } else {
        alert("getUserMedia() Not Supported")
    }
}

The startVideo() function is nearly identical to the one we created for the last example. ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.