38
Finally, we move the piece we found in board to the current location we are filling in
newBoard. Then we set the piece in the board array to false so that when we test for
the next piece, we won’t try to use the same piece we just found. When we are done
filling up newBoard, we return it as the newly randomized array of puzzle pieces:
newBoard[i][j] = board[rndCol][rndRow];
board[rndCol][rndRow] = false;
}
} return newBoard;
}
Drawing the screen
The drawScreen() function is the heart of this application. It is called on an interval
and then used to update the video frames and to draw the puzzle pieces on the screen.
A good portion of drawScreen() looks like applications we have built many times al‐
ready in this book. When it begins, we draw the background and a bounding box on
the screen:
function drawScreen () {
//Background
context.fillStyle = '#303030';
context.fillRect(0, 0, theCanvas.width, theCanvas.height);
//Box
context.strokeStyle = '#FFFFFF';
context.strokeRect(5, 5, theCanvas.width−10, theCanvas.height−10);
However, the primary work of this function is—you guessed it—another set of two
nested for:next loops that draw the puzzle pieces onto the canvas. This set needs to do
three things:
1. Draw a grid of puzzle pieces on the canvas based on their placement in the board
two-dimensional array.
2. Find the correct part of the video to render for each piece based on the finalCol
and finalRow properties we set in the dynamic object for each piece.
3. Draw a yellow box around the piece that has its selected property set to true.
We start our loop by finding the x and y (imageX, imageY) locations to “cut” the puzzle
piece from the video object. We do this by taking the finalRow and finalCol properties
of the dynamic piece objects we created and multiplying them by the partWidth and
partHeight, respectively. We then have the origin point (top-left x and y locations) for
the piece of the video to display:
for (var c = 0; c < cols; c++) {
for (var r = 0; r < rows; r++) {
Video on the Canvas Examples | 345