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

js implements single click to modify the table

Pure js implements a single-click editable table ...

MySQL account password modification method (summary)

Preface: In the daily use of the database, it is ...

IDEA graphic tutorial on configuring Tomcat server and publishing web projects

1. After creating the web project, you now need t...

Some understanding of absolute and relative positioning of page elements

From today on, I will regularly organize some smal...

MySql Installer 8.0.18 Visual Installation Tutorial with Pictures and Text

Table of contents 1. MySQL 8.0.18 installation 2....

HTML structured implementation method

DIV+css structure Are you learning CSS layout? Sti...

Record of the actual process of packaging and deployment of Vue project

Table of contents Preface 1. Preparation - Server...

How to use the Linux md5sum command

01. Command Overview md5sum - Calculate and verif...

Example of utf8mb4 collation in MySQL

Common utf8mb4 sorting rules in MySQL are: utf8mb...

HTML realizes real-time monitoring function of Hikvision camera

Recently the company has arranged to do some CCFA...

Native Js implementation of calendar widget

This article example shares the specific code of ...

Detailed explanation of Apache website service configuration based on Linux

As an open source software, Apache is one of the ...

MySQL joint index effective conditions and index invalid conditions

Table of contents 1. Conditions for joint index f...

Detailed explanation of samba folder sharing server configuration under centos

1. Introduction Recently I found that there are m...