HTML and CSS Reference
In-Depth Information
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 updated 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 (i.e., 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 may 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 slideIncrement = playBackW/audioElement.duration;
Now we need to calculate the x position of the slider. The x position is the sum of the
slider's starting position (the place on the canvas where the controls start plus the width
of the play/pause button: controlStartX+bW ) plus the audio's current play position. We
calculate the play position by taking the ratio we just created, sliderIncrement , and
multiplying it by the current play time of the audio clip ( audioElement.currentTime ).
That's it!
var sliderX = (playBackW,bH,controlStartX+bW) +
Now all we need to do is draw the image onto the canvas, and then test to see whether
the audio clip has ended. If it has ended, we put the play position back to the beginning
of the playback area and call audioElement.pause() to pause the audio clip. That is,
unless the loop property is sent, in which case we start playing the audio clip from the
beginning by setting the currentTime property to 0 :
context.drawImage(buttonSheet, 238,0,sliderW,bH,sliderX,controlStartY,sliderW,bH);
if (audioElement.ended && !audioElement.loop) {
audioElement.currentTime = 0;
This leads us right into our next topic, handling the play/pause button.
Search WWH ::

Custom Search