Online Book Reader

Home Category

HTML5 Canvas [114]

By Root 6602 0
If so, we detect a hit.

First, we test the play button. Notice that those variables we created to represent the upper-left x and y locations of the button (playX and playY) help us make this calculation. They also help us because the names of the buttons self-document what we are trying to accomplish in each test of this function.

If the play button has been clicked, and the video paused property is true, we call the play() function of the video to start playing:

//Hit Play

if ( (mouseY >= playY) && (mouseY <= playY+bH) && (mouseX >= playX) &&

(mouseX <= playX+bW) ) {

if (videoElement.paused) {

videoElement.play();

}

If the stop button was clicked, we set the paused property of the video to true, and set the currentTime property to 0 so that the video will return to the first frame:

//Hit Stop

if ( (mouseY >= stopY) && (mouseY <= stopY+bH) && (mouseX >= stopX) &&

(mouseX <= stopX+bW) ) {

videoElement.pause();

videoElement.currentTime = 0;

}

If the pause button is clicked and the paused property of the video is false, we call the pause() function of the video to—you guessed it—pause the video on the current frame. If the paused property is true, we call the play() function of the video so it will resume playing:

//Hit Pause

if ( (mouseY >= pauseY) && (mouseY <= pauseY+bH) && (mouseX >= pauseX) &&

(mouseX <= pauseX+bW) ) {

if (videoElement.paused == false) {

videoElement.pause();

} else {

videoElement.play();

}

}

Figure 6-12 shows what the canvas looks like when the video is displayed with controls.

NOTE

You will notice an odd relationship between the play and pause buttons. When one is “on,” the other is “off.” This is because we have only one property to look at: paused. There is a property named playing that exists in the HTML5 specification, but it did not work in all browsers, so we only used paused. In reality, you could have only one button and swap out the play or paused graphic depending on the paused state. That would make these controls work more like the default HTML video controls.

Figure 6-12. Canvas video player buttons

Example 6-11 shows the full source code for this application.

Example 6-11. Canvas video with controls

CH6EX11: Canvas Video With Controls