Canvas Video Puzzle

Now we arrive at the most involved example of this section. We are going to create a puzzle game based on the video we have displayed on the canvas, illustrated in Figure 6-10. Here are the steps showing how the game will operate:

  1. We will load the video onto the canvas but not display it.

  2. We will decide how many parts we want to have in our puzzle.

  3. We will create a board array that holds all the puzzle pieces.

  4. The pieces will be displayed in a 4×4 grid.

  5. We will randomize the pieces on the board to mix up the puzzle.

  6. We will add an event listener for the mouse button.

  7. We will set an interval to call drawScreen().

  8. We will wait for the user to click a puzzle piece.

  9. While we are waiting, the various parts of the video will play just as though they were one video.

  10. When a user clicks a puzzle piece, it will highlight in yellow.

  11. If the user has selected two pieces, we will swap their positions.

  12. The user will attempt to put the puzzle back together so that she can see the video as it was created.

Video puzzle

Figure 6-10. Video puzzle

Setting up the game

To start, we are going to set up some variables that will define the game’s playfield. Here is a rundown of the variables and how they will be used:

rows

The numbers of rows in the grid of puzzle pieces.

cols

The number of columns in the grid of puzzle pieces.

xPad

The space, in pixels, between each column.

yPad

The space, in pixels, between each row.

startXOffset ...

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.