172 Chapter 5—Canvas
Listing 5.4 Code for animating the video postcard
var running = null;
canvas.onclick = function() {
if (running) {
video.pause();
window.clearInterval(running);
running = null;
}
else {
var gap = video.duration/10;
video.play();
running = window.setInterval(function () {
if (video.currentTime < video.duration) {
// update video
context.setTransform(1,0,0,1,860,20);
context.drawImage(video,0,0,320,240);
context.strokeRect(0,0,320,240);
// update icons
var x1 = Math.floor(video.currentTime/gap)*107;
var tx = Math.floor(video.currentTime/gap)*5;
context.setTransform(1,0,0,1,10+tx,710);
context.drawImage(video,x1,0,107,80);
context.strokeRect(x1,0,107,80);
}
else {
window.clearInterval(running);
running = null;
}
},35);
}
};
As in the first animation example, the variable running contains the unique in-
terval ID of window.setInterval() and allows for controlling the animation. If a
value is assigned to running, we pause the hidden video with video.pause(), stop
copying frames by removing the interval, and set running back to null. Other-
wise, we start the video with video.play() at the first or next click and copy the
current video frame onto the canvas in the callback function of the interval ev-
ery 35 milliseconds. We continue the whole process until the video has finished
playing or the canvas is clicked again. The two attributes video.currentTime and
video.duration of the video object in the variable video can help check whether
the current playback position is still less than the total time of the video.
Drawing the copied video at the top right happens in parallel to drawing the first
frame. For the strip of mini snapshots, we use the total length of the video and the
desired number of snapshots to calculate the interval gap after which we need to
shift the anchor point x1 further right with a small gap tx. As long as x1 has the
same value, the animation in the reduced-size image keeps running. If x1 is shift-
ed to the right, the last frame remains static and the animation continues running