Image processing with HTML5 technology: a sliding jigsaw puzzle game-

Source: Internet
Author: User
HTML5 has many features that can integrate multimedia into webpages. You can use the canvas Element to fill the blank canvas with lines, load image files, and even animation effects. In this article, I will create a slide puzzle game to demonstrate the image processing capabilities of HTML5canvas. In the network ...,. HTML5 has many features that can integrate multimedia into webpages. You can use the canvas Element to fill the blank canvas with lines, load image files, and even animation effects.

In this article, I will create a slide puzzle game to demonstrate the image processing capabilities of HTML5 canvas.
Use the canvas label in the webpage to create the canvas.

The width and height of the canvas are measured in pixels. If the two are not specified, their default width is 300px and the height is 150px. You need to use the canvas context to draw a graph. You can use a script to call getContext () to obtain the context. W3C defines it as two-dimensional, or 2d. To initialize the context, use the following method:

  1. Document. getElementById ("vanvas"). getContext ("2d ");

The next step is to display images on the canvas. The API only provides the drawImage () method. However, there are three call methods. The most common parameters are the input three parameters: the image object and the x and y coordinates of the image relative to the canvas.

  1. DrawImage (image, x, y );

You can also add two parameters to set the image width and height.

  1. DrawImage (image, x, y, width, height );

The most complex drawImage function has nine parameters: image object, image x coordinate, image y coordinate, image width, Image Height, target x coordinate, and target y coordinate, target width and height. The last four parameters are mainly used to capture the original image for display, such as local amplification and cutting. The above is the image processing method. Let's do an exercise.

  1. Easy

  2. Hard

  • The DIV above includes another HTML5 Tag: range input, which allows you to drag and drop the slider to select a value. Let's talk about how to interact with range input in the puzzle. So far, ie and firefox do not support this label.
    Now, as I said above, we need context to draw images on the canvas.

    1. Var context = document. getElementById ("puzzle"). getContext ("2d ");

    By the way, we also need an image, which is included in the example, or we can find an image of the same size as the canvas.

    1. Var img = new Image ();
    2. Img. src = 'HTTP: // ';
    3. Img. addEventListener ('load', drawTiles, false );

    This event ensures that the image is loaded and then placed into the canvas. Next we use range input to set the number of puzzles. The data range is from 3 to 5 (several rows and columns ).

    1. Var boardSize = document. getElementById ('puzzle'). width;
    2. Var tileCount = document. getElementById ('Scale'). value;

    With the above two values, you can calculate the size of a puzzle.

    1. Var tileSize = boardSize/tileCount;

    OK. Let's start creating the canvas.

    1. Var boardParts = new Object;
    2. SetBoard ();

    SetBoard () is used to initialize the dashboard. to simulate the display of this canvas, we use a two-dimensional array. However, the process of using JavaScript to create such an array is not very elegant. We first define a plane array, and each array then defines an array. In this puzzle game, each element is an object with the grid location where x and y coordinate records are located. Therefore, each object has two coordinates. The first coordinate is the array coordinate, indicating its position on the canvas. The other coordinate is the x and y attributes of the object, which records the position of the puzzle image. If the two coordinates are the same, the positions are correct.
    To achieve this goal, we swap their locations during initialization. In this way, the puzzle is not in the correct position.

    1. Function setBoard (){
    2. BoardParts = new Array (tileCount );
    3. For (var I = 0; I <tileCount; ++ I ){
    4. BoardParts [I] = new Array (tileCount );
    5. For (var j = 0; j <tileCount; ++ j ){
    6. BoardParts [I] [j] = new Object;
    7. BoardParts [I] [j]. x = (tileCount-1)-I;
    8. BoardParts [I] [j]. y = (tileCount-1)-j;
    9. }
    10. }
    11. EmptyLoc. x = boardParts [tileCount-1] [tileCount-1]. x;
    12. EmptyLoc. y = boardParts [tileCount-1] [tileCount-1]. y;
    13. Solved = false;
    14. }

    We have not defined the last three variables.
    We must track the location of the blank puzzle and record the user's clicked location.

    1. Var clickLoc = new Object;
    2. ClickLoc. x = 0;
    3. ClickLoc. y = 0;
    4. Var
    5. EmptyLoc = new Object;
    6. EmptyLoc. x = 0;
    7. EmptyLoc. y = 0;

    The final variable indicates whether the puzzle is complete.

    1. Var solved = false;

    After finding the correct position for all the puzzles, set it to true.
    Now we need some methods related to solving puzzles.
    First, define a trigger event for rang input. When it changes, we need to recalculate the number and size of the puzzle.

    1. Document. getElementById ('Scale'). onchange = function (){

    2. TileCount = this. value;
    3. TileSize = boardSize/
    4. TileCount;
    5. SetBoard ();

    6. DrawTiles ();
    7. };

    You also need to track the mouse passing through the puzzle and which one is clicked.

    1. Document. getElementById ('puzzle'). onmousemove = function (e)
    2. {
    3. ClickLoc. x = Math. floor (e. pageX-this. offsetLeft )/
    4. TileSize );
    5. ClickLoc. y = Math. floor (e. pageY-
    6. This. offsetTop)/tileSize );
    7. };
    8. Document. getElementById ('puzzle'). onclick
    9. = Function (){
    10. If (distance (clickLoc. x, clickLoc. y,
    11. EmptyLoc. x, emptyLoc. y) = 1 ){

    12. SlideTile (emptyLoc, clickLoc );

    13. DrawTiles ();
    14. }
    15. If (solved)
    16. {
    17. Alert ("You solved
    18. It! ");
    19. }
    20. };

    Some browsers will pop up a dialog box before redrawing the canvas. to prevent it from happening, you must use a delay.

    1. If (solved ){
    2. SetTimeout (function () {alert ("You solved
    3. It! ") ;}, 500 );
    4. }

    When a puzzle is clicked, we need to know whether its surroundings can be moved. The determination method is that the total distance from the current location to the blank location can be moved when it is 1.
    To put it simply, if x is the same, you must determine whether the distance of y is 1, and if y is the same, you must determine whether the distance of x is 1.

    1. Function distance (x1, y1, x2, y2 ){
    2. Return Math. abs (x1-
    3. X2) + Math. abs (y1-y2 );
    4. }

    The practice of moving a puzzle is to copy the coordinates of the clicked puzzle to an empty position. Then, set the click position to a blank coordinate.

    1. Function slideTile (toLoc, fromLoc ){
    2. If (! Solved)
    3. {
    4. BoardParts [toLoc. x] [toLoc. y]. x =
    5. BoardParts [fromLoc. x] [fromLoc. y]. x;

    6. BoardParts [toLoc. x] [toLoc. y]. y =
    7. BoardParts [fromLoc. x] [fromLoc. y]. y;

    8. BoardParts [fromLoc. x] [fromLoc. y]. x = tileCount-
    9. 1;

    10. BoardParts [fromLoc. x] [fromLoc. y]. y = tileCount-
    11. 1;
    12. ToLoc. x =
    13. FromLoc. x;
    14. ToLoc. y =
    15. FromLoc. y;

    16. CheckSolved ();
    17. }
    18. }

    Once the puzzle moves, we need to check whether it is all in the correct position.

    1. Function checkSolved (){
    2. Var flag =
    3. True;
    4. For (var I = 0; I <tileCount; ++ I)
    5. {
    6. For (var j = 0; j <
    7. TileCount; ++ j)
    8. {
    9. If
    10. (BoardParts [I] [j]. x! = I | boardParts [I] [j]. y! = J)
    11. {

    12. Flag =
    13. False;

    14. }
    15. }

    16. }
    17. Solved = flag;
    18. }

    If a function is incorrect, false is returned; otherwise, true is returned.
    Finally, redraw the clicked puzzle to a new position.

    1. Function drawTiles (){
    2. Context. clearRect (0, 0, boardSize, boardSize );
    3. For (var I = 0; I <tileCount; ++ I ){
    4. For (var j = 0; j <tileCount; ++ j ){
    5. Var x = boardParts [I] [j]. x;
    6. Var y = boardParts [I] [j]. y;
    7. If (I! = EmptyLoc. x | j! = EmptyLoc. y | solved = true ){
    8. Context. drawImage (img, x * tileSize, y * tileSize,
    9. I * tileSize, j * tileSize, tileSize, tileSize );
    10. }
    11. }
    12. }
    13. }

    When drawing a puzzle, this function prevents blank positions from being matched when filling the canvas, because you can choose different difficulty options in the game.

    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.