js+canvas implements sliding puzzle verification code function
This article mainly introduces the js canvas implementation of the sliding puzzle verification code function. This article combines the example code to introduce it step by step in very detail. Friends in need can refer to it
The picture above shows the sliding puzzle verification code of NetEase Cloud Shield. It should have a special picture library, and the cropping position is fixed. My idea is to randomly generate pictures, randomly generate positions, and then use canvas to cut out the sliders and background images. The specific steps are described below.
First find a random picture and render it on the canvas. Here #canvas is used as the canvas and #block is used as the cropped small slider.
<canvas width="310" height="155" id="canvas"></canvas>
<canvas width="310" height="155" id="block"></canvas>
var canvas = document.getElementById('canvas')
var block = document.getElementById('block')
var canvas_ctx = canvas.getContext('2d')
var block_ctx = block.getContext('2d')
var img = document.createElement('img')
img.onload = function() {
canvas_ctx.drawImage(img, 0, 0, 310, 155)
block_ctx.drawImage(img, 0, 0, 310, 155)
};
img.src = 'img.jpg'
Let’s consider how to cut out the shape of the puzzle. The shape of the puzzle is more complicated. First we draw a square and then the top The code is written as:
var x = 150, y = 40, w = 42, r = 10, PI = Math.PI
function draw(ctx) {
ctx.beginPath()
ctx.moveTo(x, y)
ctx.lineTo(x + w, y)
ctx.lineTo(x + w, y + w)
ctx.lineTo(x, y + w)
ctx.clip()
}
draw(canvas_ctx)
draw(block_ctx)
x, y are the coordinates of the upper left corner of the square. Now just write the random number used when generating later, and w is the side of the square. length, r is the radius of the circle behind which the notch is drawn. We first encapsulate the drawing process with functions to facilitate simultaneous manipulation of the background and slider later. Use the clip() method to crop the image and generate a square.
Next draw the circles on the top and right side of the square:
function draw(ctx) {
ctx.beginPath()
ctx.moveTo(x,y)
+ ctx.lineTo(x+w/2,y)
+ ctx.arc(x+w/2,y-r+2, r,0,2*PI) //
+ ctx.lineTo(x+w/2,y)
ctx.lineTo(x+w,y)
+ ctx.lineTo(x+w,y+w/2)
+ ctx.arc(x+w+r-2,y+w/2,r,0,2*PI) //
+ ctx.lineTo(x+w,y+w/2)
ctx.lineTo(x+w,y+w)
ctx.lineTo(x,y+w)
ctx.lineTo(x,y)
ctx.clip()
}

function draw(ctx) {
ctx.beginPath()
...
ctx.lineTo(x,y)
ctx.clip()
+ ctx.beginPath()
+ ctx.arc(x,y+w/2, r,1.5*PI,0.5*PI) // 只需要画正方形内的半圆就行,方便背景图片的裁剪
+ ctx.globalCompositeOperation = "xor"
+ ctx.fill()
}

img.onload = function() {
ctx.drawImage(img, 0, 0, 310, 155)
block_ctx.drawImage(img, 0, 0, 310, 155)
+ var blockWidth = w + r * 2
+ var _y = y - r * 2 + 2 // 滑块实际的y坐标
+ var ImageData = block_ctx.getImageData(x, _y, blockWidth, blockWidth)
+ block.width = blockWidth
+ block_ctx.putImageData(ImageData, 0, _y)
}

- function draw(ctx) {
+ function draw(ctx, operation) {
...
- ctx.clip()
+ ctx.fillStyle = '#fff'
+ ctx[operation]()
...
}
+ draw(canvas_ctx, 'fill')
+ draw(block_ctx, 'clip')
##The next step is to write the style Ok, skip it:
Then we write the drag event. We can record the mouse position when the mouse is pressed, and then set the slider when dragging. left value. Finally, when the mouse is released, the left value of the slider at this time and the x value when the slider was first cropped are judged. If they are within a certain range, the verification is passed, otherwise the verification fails.
Finally add random pictures and random cutting positions, and it’s basically ok. In addition, you can judge the change of the y-axis when the mouse moves to determine whether it is operated by a "human". Of course, web security is such a mess, so I won't go into details and just make a simple judgment.
Because there is no border or shadow added to the edge of the slice, the slider of some pictures is not highly identifiable and needs to be improved later (actually I haven't messed with it yet - -), I hope Someone who understands this can help me improve it //
The code behind is a bit messy, so I won’t post it here. To view the complete code, click here for the demo address and click here
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
SSH Jquery Ajax framework integrationJQuery Ajax Struts2 Hibernate framework integration to achieve complete login registrationThe similarities and differences between ajax and traditional web development##
The above is the detailed content of js+canvas implements sliding puzzle verification code function. For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.






