Click-and-Drag Volume Slider

So now we make it to the last, but certainly not least, piece of functionality for the audio player: the volume slider. The volume slider is an interactive control allowing the user to manipulate it by sliding it right or left to control the volume of the playing audio element. Before we create the volume slider, we need to define some boundaries for its usage:

  • The slider never moves on the y-axis; it will always keep a y value.

  • The farther the volume slider is to the right (the greater the x value), the higher the volume.

  • The slider moves on the x-axis but is bounded by the starting x value of the volume slider image—volumeSliderStart on the left and volumeSliderEnd on the right.

  • When the user clicks on the volume slider, we will assume that the user wants to set the volume, so we will start “dragging” the slider. This means that if the user moves the mouse on the x-axis, we will move the slider accordingly.

  • When the user takes his finger off the mouse button, we will assume that he no longer wishes to set the volume, and we still stop “dragging” the slider.

  • The volume will be set based on the slider’s position on the x-axis in relation to the volumeSliderStart plus a ratio (volumeIncrement) that we create describing how much volume to increase or decrease based on where the slider rests.

Volume slider variables

Now that we have thoroughly confused you, let’s talk about the process in depth. First, we start with the canvasApp() function. In canvasApp(), we ...

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.