


Javascript combined with Flexbox to simply implement a sliding puzzle game_javascript skills
Sliding puzzle means dividing a picture into equal parts, shuffling the order (picture below), and then sliding them together to form a complete picture.
To implement a jigsaw puzzle, you need to consider how to randomly shuffle the order, how to swap the positions of two pictures, etc. However, after using Flexbox layout, you don’t need to think about this. The browser will do it for you. Flexbox is so powerful. For an introduction to Flexbox, click here.
What is used in this game is the order attribute of Flexbox layout. The order attribute can be used to control the order of Flex items.
Here I use nine canvas elements to divide the image into nine equal parts. You can also 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 it is not limited to nine-square grid, but also sixteen-square grid, etc., the above elements can be generated dynamically.
The following is the code to generate nine pictures in shuffled 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 shuffling the order of the numbers and randomly assigning them to the order attribute of each canvas element, the browser will automatically sort them for you.
I won’t go into other details about the code. Here’s how to swap the positions of two pictures. It’s surprisingly simple:
var order1 = item.style.order; var order2 = target.style.order;
You only need to exchange the order attribute values of both parties.
Full code
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" /> <meta content="yes" name="apple-mobile-web-app-capable" /> <meta content="black" name="apple-mobile-web-app-status-bar-style" /> <meta content="telephone=no" name="format-detection" /> <title></title> <style> html, body { height: 100%; } body { margin: 0; padding: 0; overflow: hidden; } .wrap { display: flex; flex-wrap: wrap; width: 100%; height: 100%; overflow: hidden; } .wrap canvas { width: 33.3333%; height: 33.3333%; border: 1px solid red; box-sizing: border-box; } </style> </head> <body> <div class="wrap"> <canvas data-value="1"></canvas> <canvas data-value="2"></canvas> <canvas data-value="3"></canvas> <canvas data-value="4"></canvas> <canvas data-value="5"></canvas> <canvas data-value="6"></canvas> <canvas data-value="7"></canvas> <canvas data-value="8"></canvas> <canvas data-value="9"></canvas> </div> <script> var $ = function (el) { return document.querySelector(el); }; var touchMove, touchEnd; 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); }); }); document.addEventListener("touchstart", function (e) { var target = e.target; if (e.target.tagName.toLowerCase() !== "canvas") { return; } var ctx = target.getContext("2d"); var image = ctx.getImageData(0, 0, target.width, target.height); var obj = target.cloneNode(true); obj.getContext("2d").putImageData(image, 0, 0); var top = target.getBoundingClientRect().top, left = target.getBoundingClientRect().left; obj.style.cssText = "position: absolute; top: " + top + "px; left: " + left + "px"; document.body.appendChild(obj); var point = {"x": e.touches[0].pageX, "y": e.touches[0].pageY}; document.addEventListener("touchmove", touchMove = function (e) { obj.style.cssText = "position: absolute; top:" + (e.touches[0].pageY - point.y + top) + "px; left: " + (e.touches[0].pageX - point.x + left) + "px"; }); document.addEventListener("touchend", touchEnd = function (e) { var pos = {"x": e.changedTouches[0].pageX, "y": e.changedTouches[0].pageY}; [].forEach.call(document.querySelectorAll(".wrap canvas"), function (item, i) { var offset = item.getBoundingClientRect(); if (pos.x > offset.left && pos.x < (offset.left + item.width) && pos.y > offset.top && pos.y < (offset.top + item.height)) { var order1 = item.style.order; var order2 = target.style.order; if (obj.parentNode) { document.body.removeChild(obj); } item.style.order = order2; target.style.order = order1; } }); document.removeEventListener("touchmove", touchMove); document.removeEventListener("touchend", touchEnd); }) }) </script> </body> </html>
When you are testing, it is best to use Google emulator or mobile phone to open it, because only mobile touch events are supported.
Only the basic functions are implemented in the code, and the complete functions are not implemented.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
