Click here to Skip to main content
Click here to Skip to main content

Jigsaw Puzzle Game in HTML5

, 15 Apr 2012
Rate this:
Please Sign up or sign in to vote.
This article explains, how to create Jigsaw puzzle in HTML5 Canvas.

Download JigsawPuzzleGameIn-Html5.zip (773.2 KB)

 

Introduction

HTML5 is getting famous day by day. Some fantastic and amazing games have been building using HTML5. So I thought to create Jigsaw game using HTML 5. It is very famous game to arrange a blocks to complete image. I used HTML5 canvas which is very handy and efficient way to render image.

Create Image Blocks

For saving information of each block, create imageBlock class, which will contain the information of each block. For drawing the image block in the canvas, we will simply get block information from array and draw it accordingly.

 function imageBlock(no, x, y) {

    this.no = no;
    this.x = x;
    this.y = y;
    this.isSelected = false;
 }
    

For breaking image into the parts, we need to push each imageBlock into the array and set the random x and y coordinates for each block. We also prepare final destination array having coordinates for each block. This array helps us to get information on drop of the image block and also checking how many image blocks has right position.

 function SetImageBlock() {

    var total = TOTAL_PIECES;
    imageBlockList = new Array();
    blockList = new Array();

    var x1 = BLOCK_IMG_WIDTH + 20;
    var x2 = canvas.width - 50;
    var y2 = BLOCK_IMG_HEIGHT;

    for (var i = 0; i < total; i++) {

        var randomX = randomXtoY(x1, x2, 2);
        var randomY = randomXtoY(0, y2, 2);
       
        var imgBlock = new imageBlock(i, randomX, randomY);

        imageBlockList.push(imgBlock);

        var x = (i % TOTAL_COLUMNS) * BLOCK_WIDTH;
        var y = Math.floor(i / TOTAL_COLUMNS) * BLOCK_HEIGHT;

        var block = new imageBlock(i, x, y);
        blockList.push(block);

    }

 }
    

Get all image Blocks information from array and if block is not selected then simply draw it.

 function drawAllImages() {

    for (var i = 0; i < imageBlockList.length; i++) {
        var imgBlock = imageBlockList[i];
        if (imgBlock.isSelected == false) {

            drawImageBlock(imgBlock);
        }
    }
 }
    

Use drawImage method of the canvas for drawing block. Calculate source x and y coordinates based on block number and pass them to the ctx.drawImage(...) method to draw image block. This method read image based on provided information and draw it into canvas on given destination coordinates.

 function drawImageBlock(imgBlock) {
         
    drawFinalImage(imgBlock.no, imgBlock.x, imgBlock.y, BLOCK_WIDTH, BLOCK_HEIGHT);
 
 }

 function drawFinalImage(index, destX, destY, destWidth, destHeight) {

    ctx.save();

    var srcX = (index % TOTAL_COLUMNS) * IMG_WIDTH;
    var srcY = Math.floor(index / TOTAL_COLUMNS) * IMG_HEIGHT;

    ctx.drawImage(image1, srcX, srcY, IMG_WIDTH, IMG_HEIGHT, destX, destY, destWidth, destHeight);

    ctx.restore();
 }

Drag Image Block

For drag image block, register mouse down, up and move event of canvas.

 // register events
 canvas.onmousedown = handleOnMouseDown;
 canvas.onmouseup = handleOnMouseUp;
 canvas.onmouseout = handleOnMouseOut;
 canvas.onmousemove = handleOnMouseMove;

On mouse down simple find imageBlock in the collection lay between click positions of mouse. If item found then assign it to the selectedBlock object.

 function handleOnMouseDown(e) {

    // remove old selected
    if (selectedBlock != null) {

        imageBlockList[selectedBlock.no].isSelected = false;

    }

    selectedBlock = GetImageBlock(imageBlockList, e.pageX, e.pageY);

    if (selectedBlock) {
        imageBlockList[selectedBlock.no].isSelected = true;
    }

 }

On mouse move if it has selectedBlock then set new x and y position of the selected block and redraw the canvas.

 function handleOnMouseMove(e) {

    if (selectedBlock) {

        selectedBlock.x = e.pageX  - 25;
        selectedBlock.y = e.pageY  - 25;

        DrawGame();
    }
 }

On mouse up check if it is on the block and block does not has image then set source image coordinates accordingly and redraw the canvas. If game is finished with this move then make it finish.

 function handleOnMouseUp(e) {

    if (selectedBlock) {
        var index = selectedBlock.no;
     
        var block = GetImageBlock(blockList, e.pageX, e.pageY);
        if (block) {

            var blockOldImage = GetImageBlockOnEqual(imageBlockList, block.x, block.y);
            if (blockOldImage == null) {
                imageBlockList[index].x = block.x;
                imageBlockList[index].y = block.y;
            }
        }
        else {
            imageBlockList[index].x = selectedBlock.x;
            imageBlockList[index].y = selectedBlock.y;
        }

        imageBlockList[index].isSelected = false;
        selectedBlock = null;
        DrawGame();

        if (isFinished()) {
            OnFinished();
        }
    }
 }

Play Audio on Finish

On the finish of the game for playing music simply creates audio object using javaScript and set its source and play it.

 function OnFinished() {

    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', 'Audio/finish.mp3');
    audioElement.play();

    .
    .
    .
 }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shakeel Iqbal
Software Developer (Senior) TEO
Pakistan Pakistan
Passion and positive dedication is essential part of success. I believe on hardworking and sharing knowledge with others. I always try to be a better than I am and think positive for positive result.
 
My Blogs
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionNot Running Well In Safari 5.1.7 PinmemberMember 1079745520-May-14 21:51 
QuestionChanging Difficulties PinmemberKrs Joseph17-Oct-12 6:31 
GeneralMy vote of 4 PinmemberDonsw23-Sep-12 6:32 
QuestionProblem in medium level Pinmemberashkap0322-May-12 22:33 
AnswerRe: Problem in medium level PinmemberMember 1079745520-May-14 21:49 
GeneralMy vote of 3 PinmemberSachin Kumar, Mindfire23-Apr-12 19:59 
GeneralMy vote of 4 PinmemberMuhammad Ghufran22-Apr-12 23:44 
QuestionNice Article but browser dependent Pinmembernainakarri16-Apr-12 1:17 
AnswerRe: Nice Article but browser dependent PinmemberShakeel Iqbal16-Apr-12 1:23 
Thank. It will only work in those browser who supports HTML5. it will also work in IE9.
-----------------------------
Shakeel Iqbal
------------------------------

GeneralMy vote of 4 PinmemberPraveen Meghwal15-Apr-12 23:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 16 Apr 2012
Article Copyright 2012 by Shakeel Iqbal
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid