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:
We will load the video onto the canvas but not display it.
We will decide how many parts we want to have in our puzzle.
We will create a
board
array that holds all the puzzle pieces.The pieces will be displayed in a 4×4 grid.
We will randomize the pieces on the board to mix up the puzzle.
We will add an event listener for the mouse button.
We will set an interval to call
drawScreen()
.We will wait for the user to click a puzzle piece.
While we are waiting, the various parts of the video will play just as though they were one video.
When a user clicks a puzzle piece, it will highlight in yellow.
If the user has selected two pieces, we will swap their positions.
The user will attempt to put the puzzle back together so that she can see the video as it was created.
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.