Top Good Web Design

Web Designer

Create a Jigsaw Puzzle Using jQuery and PHP

Almost everyone, at one point during childhood, has played jigsaw puzzles. Today I am going to show you how to create a jigsaw puzzle using jQuery and PHP.

Lets start creating puzzles. I know that you must be waiting to see the puzzle in action. I am not going to keep you guessing. Here is the sample demo of the puzzle and download of tutorial files.

Now you got your wish. So lets move onto creating the puzzle.



Splitting an Image into Smaller Parts

First thing we have to do is choose an image for the puzzle. Only jpg images can be used in this example. I am going to use the 1stwebdesigner header image for the puzzle. Once you choose the image it has to be split into smaller images to create the puzzle components.

There are a lot of online tools available for splitting images. But I am going to use my own php code to split the image. The purpose of this tutorial is to make the puzzle. So I am not going to explain the whole PHP code for splitting images. I’ll just explain the necessary configurations.


    $image_file = 'puzzle.jpg';

    $src = imagecreatefromjpeg($image_file);
    list($width, $height, $type, $attr) = getimagesize($image_file);

    $split_size = '150';

    $cal_width  = $width % $split_size;
    $cal_height = $height % $split_size;

    if ($cal_width > 0) {
        $new_width = intval($width / $split_size) * $split_size + 100;
    } else {
        $new_width = $width;
    if ($cal_height > 0) {
        $new_height = intval($height / $split_size) * $split_size + 100;
    } else {
        $new_height = $height;

    if ($width > 1200) {
        $width = 1200;
        $new_width = 1200;

    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($image_file);

    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    imagejpeg($image_p, $image_file, 100);

    $x_comp = intval($new_width / $split_size);
    $y_comp = intval($new_height / $split_size);

    $winning_string = '';
    $image_names = '';

    $src = imagecreatefromjpeg($image_file);
    $dest = imagecreatetruecolor($split_size, $split_size);

    for ($y = 0; $y < $y_comp; $y++) {
        for ($i = 0; $i < $x_comp; $i++) {
            $characters = 'abcdefghijklmnopqrstuvwxyz';
            $ran_string = '';
            for ($p = 0; $p < 4; $p++) {
                $ran_string .= $characters[mt_rand(0, strlen($characters) - 1)];

            imagecopy($dest, $src, 0, 0, $i * $split_size, $y * $split_size, $split_size, $split_size);
            imagejpeg($dest, "images/$ran_string.jpg");

            $winning_string .= $ran_string;
            $image_names .= $ran_string . ",";

    $image_names = substr($image_names, 0, -1);
    $images = explode(',', $image_names);

Code Explanation

  • First you have to provide the name of your image in the $image_file variable. I have used puzzle.jpg as the name and it should be on the same path as the file which contains the above php code.
  • In line 8 you see the variable $split_size. It is defined in pixels and you can change the value if you want. I have used 150. So the image will be split into parts of 150px * 150px images.
  • Also make sure total width and height of your image is a multiple of 150. If it is not a multiple of 150 some parts of the original image will be removed when split.
  • Then in line 54 you should specify a folder for the split images to be stored. I have used the folder name as images.

Now what you have to do is download the tutorial files first. Then copy it to your web server and give necessary permissions to folders. Then open the split.php file and make the changes mentioned above or keep the default values.

Once you execute it in the browser you will get a output like the following.

Puzzle Winning and Load Strings

You should keep both Winning String and Load String as shown in the above screen. Now we are done with the image split. So lets move onto the next section.

Creating the Puzzle Using Jquery

I have already created images for our puzzle in the images folder. Now we have to create the puzzle by loading the puzzle images. Before that we need to enable Drag and Drop support using Jquery UI library. So I’ll show you the necessary files to be included.

I have downloaded and included the necessary files of jQuery UI Library in the tutorial files. You can use the following code to include the files related to our tutorial.

<html lang='en'>
	<title>Jquery Drag and Drop Puzzle</title>
	<script src="jquery-1.7.2.js" type="text/javascript"></script>
	<script src="ui/jquery.ui.core.js" type="text/javascript"></script>
	<script src="ui/jquery.ui.widget.js" type="text/javascript"></script>
	<script src="ui/jquery.ui.mouse.js" type="text/javascript"></script>
	<script src="ui/jquery.ui.sortable.js" type="text/javascript"></script>
	<link rel="stylesheet" href="demos.css">


In the code you can see the file called jquery.ui.sortable.js. It is used to handle the drag and drop and then sort the items inside the given container. This is called Sortable in Jquery UI library. Once you make an element sortable, you will be able to both drag and drop items inside that element. You can make item sortable using the following code.

Jquery Code for Making Unordered List Sortable


Unordered List with Items

<ul id='sortable'>
      <li>Item 1</li>
      <li>Item 2</li>

Above codes will enable sortable event on all the li items inside the ul container with the id sortable

Basic CSS Styles for Sortable Element

<style type='text/css'>
	#sortable { list-style-type: none; margin: 0; padding: 0; }
	#sortable li { float: left;}
            text-align: center;
            padding: 20px;
            font-size: 30px;
            text-shadow: 1px 1px 1px rgb(21, 23, 28);

Loading Images for the Drag and Drop Puzzle

Puzzle Before Starting

Now I am going to display the image parts as puzzle. We can use the following PHP code with small configurations to load the images. This code is located in puzzle.php file on the project folder. You can run the puzzle.php file in your web server to directly execute the demo. Now get ready with the Winning String we created earlier.

            $image_names = "ilsc,scmz,lsea,derv,logi,eyen,vkxl,ihrx,mwgc,bwdk,rfwb,oezh";
            $images = explode(',', $image_names);

            $new_width = "900";
            $new_height= "300";
	    $split_size= "150";

            echo "<ul id='sortable' style='width:" . $new_width . "px;height:" . $new_height . "px;'>";

            foreach ($images as $key => $image_name) {
                echo "<li class='ui-state-default' id='recordArr_$image_name' style='width:" . $split_size . "px;height:" . $split_size . "px;'>
                            <img src='images/$image_name.jpg' /></li>";

            echo "</ul>";

Code Explanation

  • First enter the Load String we generated earlier into the variable called $image_names. Keep it as it is if you are going to use the default demo.
  • Each time you change the image of your puzzle and split it with the split.php file, you have to assign the Load String here.
  • Then we have variables called $new_width and $new_height. These values should be defined according to the number of parts in your puzzle.
  • We created 150px * 150px images and we have 6 images horizontally since original image I used was 900*300px. So $new_width should be 150*6 = 900. Also we have 2 images vertically. So $new_height should be 150*2 = 300. Configure those values according to size of your image. Also $split_size is set to 150 since we are using 150*150 images.
  • Then we load all the images for the puzzle inside unordered list. You don’t have to do anything there.
  • Now we have completed displaying the puzzle images.

You can see the puzzle on your screen and try to drag and drop images. You must be wondering why the puzzle is not working. That’s because we haven’t made the puzzle sortable yet. That’s where the magic happens. So lets make it sortable.

Making the Puzzle Sortable

Puzzle After Starting

Include the following code snippet on the head section of your document after the js and css files.

         <script type="text/javascript">
            $(function() {
                    opacity: 0.6,
                    cursor: 'move',
                    update: function() {



Now you can drag and drop the images and you will be able to see that images are changing in the puzzle. But there is no way you can check whether puzzle is solved or not unless its a very simple one. So now I am going to tell you how to check whether puzzle is solved using a very simple method.

Identify the Winning Moment

Winning Moment of Puzzle

Here is the code that will notify you when the puzzle is solved. Include it inside the update function of the code we created in the previous section

         <script type="text/javascript">
            $(function() {
                    opacity: 0.6,
                    cursor: 'move',
                    update: function() {
                        var winningString = "oezh,rfwb,lsea,vkxl,ihrx,ilsc,eyen,mwgc,derv,logi,bwdk,scmz";
                        var currentString = '';

                        $('#sortable li').each(function(){
                            var imageId = $(this).attr("id");
                            currentString += imageId.replace("recordArr_", "")+",";

                        currentString = currentString.substr(0,(currentString.length) -1);

                        if(currentString == winningString){
                            alert("You  Won");


Code Explanation

  • Each time you move an item in the puzzle the update function will be executed.
  • First insert the Winning String we got earlier when creating images, into winningString variable.
  • Then the code will get the current positions of the images in the puzzle and creates a string with current item order.
  • Next we check whether current string matches the winning string and displays the winning message.

We have completed our tutorial on creating puzzles and now you can enjoy creating and solving puzzles.

Bonus Tip

Have you tried fixing the puzzle yet ?

You might have done it pretty easily since only 12 parts are available in the demo. But when the number of parts increases it will be very difficult unless you find out the correct method.

If you are a designer or developer who has knowledge in working with HTML DOM, you will be able to find the correct method. Drag and drop images a few times and see how the images are positioning. Then try to match that with how the HTML DOM works when you add and remove elements dynamically. I am sure that you will be able to figure it out.

So you can learn about the DOM while having fun with fixing puzzles. Let me know if you figure it out using the comments section.

Whats Next?

Now we have completed creating a basic puzzle using jQuery drag and drop features. What we did was manually create image parts using some php code and including those parts of the puzzle. You can extend this by allowing users to upload images and create the image parts dynamically. Then allow the users to select the puzzle from a dropdown and fix it. So you will be able to create puzzles out of any image.

Sounds good right ? Here is some more functionality you can include in your puzzle.

1. Assign a time to fix the puzzle in a given time period using javascript setTimeout function.

Puzzle with Time

2.Save image names in a database table with correct order and provide a score on how many parts have been completed inside the given time.

Display Puzzle Score

You can extend these features and create a puzzle site for users very easily. Let me know if you have any questions regarding using these puzzles or extending features. Use the instructions in the project files to execute the demo properly. Hope to hear from you.

Leave a Reply