A slide puzzle is to divide a picture into equal parts, scramble the order (below), and then slide it together into a complete picture.
To achieve a jigsaw puzzle, you need to consider how to randomly shuffle the order, how to exchange the location of two pictures, and so on. However, after using the Flexbox layout, this does not need you to consider, the browser will help you do, Flexbox is so powerful. You can click here for an introduction to Flexbox.
This game uses the order attribute of the Flexbox layout, which can be used to control the sequence of flex items.
Here I use nine canvas elements to divide the picture into nine equal parts, or you can use other methods, such as background image positioning:
<div class= "wrap" >
<canvas></canvas>
<canvas></canvas>
<canvas> </canvas>
<canvas></canvas>
<canvas></canvas>
<canvas></ canvas>
<canvas></canvas>
<canvas></canvas>
<canvas></canvas >
</div>
If not limited to nine Sudoku, but also 16 Sudoku and so on, the above elements can be dynamically generated.
The following is a nine-diagram code that generates an scrambling order:
var drawImage = function (URL) {return
new Promise (function (resolve, reject) {
var img = new Image ();
Img.onload = function () {
resolve (IMG);
};
img.src = URL;
})
};
DrawImage ("2.jpg"). Then (function (img) {
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var random = Arr.sort (function () {return math.random () > 0.5});
[].foreach.call (Document.queryselectorall ("canvas"), function (item, i) {
item.width = $ (". Wrap"). CLIENTWIDTH/3 ;
Item.height = $ (". Wrap"). Clientheight/3;
Item.style.order = Random[i];
var ctx = Item.getcontext ("2d");
Ctx.drawimage (IMG, img.width * (i% 3)/3, Img.height * Math.floor (I/3)/3, IMG.WIDTH/3, IMG.HEIGHT/3, 0, 0, item. width, item.height);
});
The key code above is:
Item.style.order = Random[i];
By disrupting the order of numbers, you randomly assign values to each of the canvas elements, so that the browser automatically sorts them for you.
As for the other details of the code, here's how to exchange the location of the two pictures, which is surprisingly simple:
var order1 = Item.style.order;
var order2 = Target.style.order;
You only need to exchange the order attribute values on both sides.
Complete code
When you do the test, it is best to use Google Simulator or mobile phone to open, because only the mobile terminal to support touch events.
The code only implements the basic functionality and does not implement the full functionality.