HTML and CSS Reference
In-Depth Information
Sliding Play Indicator
The sliding play indicator is the simplest control we are going to draw onto the canvas. It is
not interactive—it just gives the user a visual indication of how much of the audio clip is left
to play.
First of all, in
canvasApp()
we need to make sure that we call the
drawScreen()
function on
an interval so that our updated controls will be displayed:
function
function
gameLoop
() {
window
.
setTimeout
(
gameLoop
,
20
);
drawScreen
()
}
gameLoop
();
NOTE
Unlike when displaying video on the canvas, we do not have to call
drawScreen()
to update the
playing audio. In JavaScript, audio plays completely separate from the canvas. Our need to call
drawScreen()
on an interval is necessary because the audio controls we are creating need to be up-
dated as the audio plays.
In the
drawScreen()
function, we need to draw the slider and background on the canvas. We
are going to “cut” all the images we display from the single
buttonSheet
image we loaded
from
audiocontrols.png
. To draw the background, we use the values we set up earlier. We use
literals (
32,0
) to locate the starting point of the image because those values do not change
on the
buttonSheet
image. However, we use the variables we created to find the width and
height, and to locate the final position of the background on the canvas:
context
.
drawImage
(
buttonSheet
,
32
,
0
,
playBackW
,
bH
,
playBackX
,
playBackY
,
playBackW
,
bH
);
Drawing the play slider is only a bit more complicated. Before we draw it, we need to create
a variable that represents the relationship between the length of playing audio and the width
of slider area. This is so we will know how far on the x-axis to move the slider based on how
much of the song has played. This might sound complicated, but it's just a simple fraction.
Divide the width of the play background (
playBackW
) by the duration of the playing audio
(
audioElement.duration
). We will store that ratio in
sliderIncrement
and use it to place
the play slider on the canvas:
var
var
slideIncrement
=
playBackW
/
audioElement
.
duration
;