Online Book Reader

Home Category

HTML5 Canvas [129]

By Root 6369 0

}

In the eventMouseUp() handler, we test to see whether the volumeSliderDrag is set to true. If so, it means that the user has released the mouse button and no longer wants to drag the volume slider. We set volumeSliderDrag to false so the slider will not move with the mouse:

if (volumeSliderDrag) {

volumeSliderDrag = false;

}

In drawScreen() we actually put the pixels to the canvas, so to speak, with the volume slider. First, we draw the background image from buttonSheet:

//vol Background

context.drawImage(buttonSheet, 32,32,volBackW,bH,volBackX,volBackY,volBackW,bH);

Next, we check to see whether volumeSliderDrag is true. If so, we make the volumeSliderX variable equal to the mouse’s x position. Then, we drop in a couple more tests to determine whether the x position of the volume slider falls outside the bounds of the volume background. These two tests make sure that the volume slider does not move past the rightmost or leftmost sides of the volume slider background, and in turn, the volume property of audioElement is not calculated to be more than 1 or less than 0:

if (volumeSliderDrag) {

volumeSliderX = mouseX;

if (volumeSliderX > volumeSliderEnd) {

volumeSliderX = volumeSliderEnd;

}

if (volumeSliderX < volumeSliderStart) {

volumeSliderX = volumeSliderStart;

}

If the volumeSliderDrag is false, we still need an x position at which to draw the slider graphic. We get this the same way we calculated the volumeSliderX when we initialized the variable in the canvasApp() function:

} else {

volumeSliderX = volumeSliderStart + (audioElement.volume*

(volBackW -sliderW));

}

Finally, we draw the slider onto the canvas:

context.drawImage(buttonSheet, 238,0,sliderW,bH,volumeSliderX,

volumeSliderY, sliderW,bH);

audioElement.volume = (volumeSliderX-volumeSliderStart) * volumeIncrement;

Figure 7-6 displays the custom controls in the browser.

Figure 7-6. Canvas sound player with custom controls

So there you have it. You can test the audio player as CH7EX5.html in the source code. The full code listing for the HTML5 Canvas audio player is shown in Example 7-5.

Example 7-5. A custom audio player on the canvas

CH7EX5: A Custom Sound Player On The Canvas