HTML and CSS Reference
In-Depth Information
}
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 topic. 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++) {
var tempPiece = board[c][r];
var imageX = tempPiece.finalCol*partWidth;
var imageY = tempPiece.finalRow*partHeight;
Now that we know the origin point of the video we will display for a particular piece
of the puzzle, we need to know where it will be placed on the canvas. While the code
below might look confusing, it's really just simple arithmetic. To find the x location
( placeX ) of a piece, multiply the partWidth times the current iterated column ( c ), then
add the current iterated column multiplied by the xPad (the number of pixels between
Search WWH ::




Custom Search