Native js to achieve puzzle effect

Native js to achieve puzzle effect

This article shares the specific code of native js to achieve the puzzle effect for your reference. The specific content is as follows

Requirement: Each time the page is refreshed, fragment images will be randomly arranged in the container on the right. Press and drag the mouse to the left. Within a certain range of the correct coordinates, the image will be automatically adsorbed. The placed fragments can no longer be dragged.

Let’s take a look at the effect first:

js code:

//Execute the initial function init();
function init() {
    //Create a fragment container var frag = document.createDocumentFragment();
    document.body.style.margin = "0px";
    //Create the left image container var ul=createE("ul",{
        width: "260px",
        height: "400px",
        backgroundImage: "url(./img/3.jpg)",
        borderRight: "1px solid #000",
        borderBottom: "1px solid #000",
        listStyle: "none",
        padding: "0px",
        margin: "0px",
        opacity: ".3",
        position: "absolute"
    })
    //Create li to display the border in the picture var li=createE("li",{
        width: "51px",
        height: "79px",
        borderLeft: "1px solid #000",
        borderTop: "1px solid #000",
        padding: "0px",
        margin: "0px",
        float: "left"
    })
    //Loop, copy li and insert it into ul for (i = 0; i < 25; i++) {
        ul.appendChild(li.cloneNode(false));
    }
    //Insert ul into the fragment container frag.appendChild(ul);
    //Create the image container on the right. Because img needs to be positioned relative to body, its parent container cannot have positioning attributes var div = createE("div",{
        width: "302px",
        height: "302px",
        border: "1px solid #000",
        marginLeft: "400px"
    })
    //Create image tags for (var j = 0; j < 5; j++) {
        for (var k = 0; k < 5; k++) {
            var img = createE("img",{
                width: "52px",
                height: "80px",
                position: "absolute",
                left: Math.floor(Math.random() * 250) + 400 + "px",
                top: Math.floor(Math.random() * 220) + "px"
            })
            img.src = "./img/img" + j + "-" + k + ".jpg";
            //Picture listens to mouseHandler events img.addEventListener("mousedown", mouseHandler);
            div.appendChild(img);
        }
    }
    //Insert div into the fragment container, and then insert frag into body frag.appendChild(div);
    document.body.appendChild(frag);
}
//Mouse event function mouseHandler(e) {
    switch (e.type) {
        case "mousedown":
            // Clear the default effect of moving the image after clicking e.preventDefault();
            console.log(this.src.match(/img\/img(.*)\.jpg/))
            //Get the number in the image path and calculate the correct position coordinates of the image var imgSrc = this.src.match(/img\/img(.*)\.jpg/)[1].split("-");
            var rightL=imgSrc[1]*52;
            var rightTop=imgSrc[0]*80;
            //If the picture is correctly placed, jump out directly if (this.style.left===rightL+"px" && this.style.top===rightTop+"px") return;
            //Set the z-index of the current image to the maximum this.style.zIndex = "999";
            //Store e.offsetX, e.offsetY and the currently clicked image object into the document document.x = e.offsetX;
            document.y = e.offsetY;
            document.elem = this;
            document.rightL=rightL;
            document.rightTop=rightTop;
            //document listens for mousemove and mouseup events document.addEventListener("mousemove", mouseHandler);
            document.addEventListener("mouseup", mouseHandler);
            break;
        case "mousemove":
            //Automatic adsorption distance var gap = 20;
            //Set the current image to move with the mouse let x=e.clientX - this.x;
            let y = e.clientY - this.y;
            this.elem.style.left = x + "px";
            this.elem.style.top = y + "px";
            //If the current image's position coordinates are within a certain range, let it automatically adsorb if (x>=this.rightL-gap &&x<=this.rightL+gap&&
                y>=this.rightTop-gap &&y<=this.rightTop+gap) {
                this.elem.style.left = this.rightL + "px";
                this.elem.style.top = this.rightTop + "px";
            }
            break;
        case "mouseup":
            //When the mouse is released, reduce the z-index of the current image this.elem.style.zIndex = "10";
            //After releasing the mouse, remove the document's mousemove and mouseup events, clear the data, and prevent content leakage this.removeEventListener("mousemove", mouseHandler);
            this.removeEventListener("mouseup", mouseHandler);
            this.elem=null;
            break;
    }
}
//Create a tag function createE(elem,styleData){
    var elem = document.createElement(elem);
    for(var prep in styleData){
        elem.style[prep]=styleData[prep];
    }
    return elem;
}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • js+canvas realizes the function of sliding puzzle verification code
  • JS realizes three effects of PC mobile terminal and embedded sliding puzzle verification code
  • js realizes the nine-square puzzle game
  • JS quickly implements mobile jigsaw puzzle games
  • JS jigsaw puzzle game object-oriented, fully commented.
  • js+html5 realizes a jigsaw puzzle game that can be played on mobile phones
  • Digital puzzle game code written in JS [learning reference]
  • JS implements a complete example of sliding puzzle verification function
  • Sample code for simulating the operation of sliding puzzle verification code using Node.js
  • Picture puzzle memory test game, web + JS version

<<:  Linux /etc/network/interfaces configuration interface method

>>:  Example of how to check the capacity of MySQL database table

Recommend

Use of Linux file command

1. Command Introduction The file command is used ...

Two ways to use react in React html

Basic Use <!DOCTYPE html> <html lang=&qu...

A brief discussion on React native APP updates

Table of contents App Update Process Rough flow c...

Implementation steps for building FastDFS file server in Linux

Table of contents 1. Software Package 2. Install ...

VMWare15 installs Mac OS system (graphic tutorial)

Installation Environment WIN10 VMware Workstation...

Completely uninstall mysql. Personal test!

Cleanly uninstall MySQL. Personally tested, this ...

Vue implements an example of pulling down and scrolling to load data

Table of contents Step 1: Installation Step 2: Ci...

About WSL configuration and modification issues in Docker

https://docs.microsoft.com/en-us/windows/wsl/wsl-...

MySQL database optimization: index implementation principle and usage analysis

This article uses examples to illustrate the prin...

Project practice of deploying Docker containers using Portainer

Table of contents 1. Background 2. Operation step...

How to choose transaction isolation level in MySQL project

introduction Let's start with our content. I ...

Solve the problem of docker pull being reset

This article introduces how to solve the problem ...

Detailed explanation of Mencached cache configuration based on Nginx

Introduction Memcached is a distributed caching s...