JavaScript implements the drag slider puzzle verification function (html5, canvas)

JavaScript implements the drag slider puzzle verification function (html5, canvas)

introduction:

Slider drag verification is now used in many places. I thought about writing one over the weekend and put it here to see if anyone can use it! Effect:

Implementation ideas:

Use a canvas to draw the source image, and then draw a filled square, so that the missing effect can be achieved (the coordinates of the square are random);

Use another canvas to draw the drag block, and use drawImage to capture the original image with the same coordinates and size as the square area in the previous step. This will be used as the verification image, and the verification image is placed on the far left.

At the drag block, press the mouse and then drag, the drag block and the verification graph will move with the mouse, and release the mouse after reaching a certain range, and verification will be performed;

If the verification is successful, the message "Verification is successful" will be displayed. If the verification is not successful, the dragged block and the verification diagram will return to the far left.

3 constructors Image constructor

//Image object ImageDraw constructor function ImageDraw(o,obj){
		this.id='',
		this.image=0, //Picture object (required)
		this.sx=0, //Start x position of the image slice (not required when displaying the entire image)
		this.sy=0, //Start y position of the image slice (not required when displaying the entire image)
		this.sWidth=0, //Start width of the image slice (no need to fill in when displaying the entire image)
		this.sHeight=0, //Starting height of image slice (no need to fill in when displaying the entire image)
		this.dx=0, //Image target x position (required)
		this.dy=0, //Image target y position (required)
		this.dWidth=0, //Image target display width (no need to fill in when width is not scaled)
		this.dHeight=0 //Image target height (no need to fill in if the height is not scaled)
		
		this.init(o,obj);
	}
	ImageDraw.prototype.init=function(o,obj){
		for(var key in o){
			this[key]=o[key];
		}
		return this;
	}
	ImageDraw.prototype.render=function(context){
		draw(context,this);
		function draw(context,obj) {
			var ctx=context;
			ctx.save();
			
			if(!obj.image || getType(obj.dx)=='undefined' || getType(obj.dy)=='undefined'){
				throw new Error("Missing parameters for drawing pictures");	
				return;
			} 
			ctx.translate(obj.dx,obj.dy);
			if(getType(obj.sx)!='undefined' && getType(obj.sy)!='undefined' && obj.sWidth && obj.sHeight && obj.dWidth && obj.dHeight){
				//Crop the image and scale it when displayed ctx.drawImage(obj.image, obj.sx, obj.sy, obj.sWidth, obj.sHeight, 0, 0, obj.dWidth, obj.dHeight);
			}else if(obj.dWidth && obj.dHeight){
				ctx.drawImage(obj.image, 0, 0, obj.dWidth, obj.dHeight); //Original image, scaled when displayed }else{
				ctx.drawImage(obj.image,0, 0); //Original image, no scaling when displayed }
			ctx.restore();
		}
	}
	ImageDraw.prototype.isPoint=function(pos){
		//The x and y of the mouse position must be greater than dx and dy respectively, and x and y must be less than dx+dWidth and dy+dHeight respectively
		if(pos.x>this.dx && pos.y>this.dy && pos.x<this.dx+this.dWidth && pos.y<this.dy+this.dHeight ){//Indicates that it is within the range of the current image object return true;
		}
		return false;
	}

Square Constructor

function Rect(o){
		this.x=0,//x coordinate this.y=0,//y coordinate this.width=100,//width this.height=40,//height this.thin=true,//thinner line		
		this.init(o);
	}
	
	Rect.prototype.init = function (o) {
		for(var key in o){
			this[key]=o[key];
		}
	}
	Rect.prototype.render = function (context) {
		this.ctx=context;
		innerRender(this);
			
		function innerRender(obj){
			var ctx=obj.ctx;
			ctx.save()
			ctx.beginPath();
			ctx.translate(obj.x,obj.y);
			
			if(obj.lineWidth){
				ctx.lineWidth=obj.lineWidth;
			}
			if(obj.thin){
				ctx.translate(0.5,0.5);
			}
			ctx.rect(0,0,obj.width,obj.height);
			if(obj.fill){//Is it filled? obj.fillStyle?(ctx.fillStyle=obj.fillStyle):null;
				ctx.fill();
			}
			if(obj.stroke){//Whether to stroke obj.strokeStyle?(ctx.strokeStyle=obj.strokeStyle):null;
				ctx.stroke();
			}	
		 	ctx.restore();
		}
	 	return this;
	}

Text Constructor

function Text(o){
		this.x=0,//x coordinate this.y=0,//y coordinate this.text='',//content this.font=null;//font this.textAlign=null;//alignment		
		this.init(o);
	}
	
	Text.prototype.init=function(o){
		for(var key in o){
			this[key]=o[key];
		}
	}
	Text.prototype.render=function(context){
		this.ctx=context;
		innerRender(this);
			
		function innerRender(obj){
			var ctx=obj.ctx;
			ctx.save()
			ctx.beginPath();
			ctx.translate(obj.x,obj.y);
			
			if(obj.font){
				ctx.font=obj.font;
			}
			if (obj.textAlign) {
				ctx.textAlign=obj.textAlign;
			}
			if(obj.fill){//Is it filled? obj.fillStyle?(ctx.fillStyle=obj.fillStyle):null;
				ctx.fillText(obj.text,0,0);
			}
		 	ctx.restore();
		}
	 	return this;
	}

Draw source graph and missing blocks

var img = new ImageDraw({image:this.imgObj[0],dx:0, dy:0 ,dWidth:640,dHeight:360},this);
		this.renderArr.push(img);
 
var x = _.getRandom (100, 580); // x is between 100-580 var y = _.getRandom (0, 300); // y is between 0-300		
		this.validPos={x:x,y:y};
		//Draw the missing block var rect = new Rect({
			x:x,
			y:y,
			width:60,
			height:60,
			fill:true,
			fillStyle:'gray'
		})
		this.renderArr.push(rect);
		
		//Draw the verification block strip var rect = new Rect({
				x:0,
				y:360,
				width:640,
				height:40,
				fill:true,
				fillStyle:'#E8E8E8'
		})
		this.renderArr.push(rect);
		
		//Draw text var text = new Text({
			x:300,
			y:390,
			text:'Drag the slider to verify',
			font:'18px serif',
			textAlign:'center',
			fill:true,
			//fillStyle:'white'
		});
		this.renderArr.push(text);

The page effect is as follows

Draw validation diagrams and drag blocks

Note: The coordinates for drawing the verification graph are the same as the coordinates for drawing the missing blocks in the previous step.

var pos = this.validPos; //The coordinates of the missing block drawn in the previous step, the verification image needs to be intercepted according to this coordinate var img = new ImageDraw({image:this.imgObj[0],sx:pos.x,sy:pos.y,sWidth:60,sHeight:60,dx:0, dy:pos.y,dWidth:60,dHeight:60},this);
this.renderArr2.push(img);
		
var img1 = new ImageDraw({image:this.imgObj[1],dx:0, dy:360 ,dWidth:40,dHeight:40},this);
this.renderArr2.push(img1);

Effect picture:

Canvas 2 add event

//Add click event to canvas canvas2.addEventListener('mousedown',this.mouseDown.bind(this));
canvas2.addEventListener('mouseup',this.mouseUp.bind(this));
canvas2.addEventListener('mousemove',this.mouseMove.bind(this));

Mouse down event

  • Record the x-coordinate when the mouse is pressed to keep the mouse from floating.
  • Change the move flag to true to prevent the slider from moving without dragging it.
Slider.prototype.mouseDown=function(e){
			var pos = _.getOffset(e); //Get the mouse position if(!this.block) return;
			if(this.block.isPoint(pos)){//The pressed position is the position of the slider this.move=true;//Indicates that it can be moved this.downX=pos.x;//Record the position where the mouse is pressed and keep moving }
	}

Mouse Move Events

  • The validation graph and slider moves by subtracting the initial X coordinate of the mouse click.
  • When it exceeds a certain range, it cannot be moved anymore to prevent it from moving out of the canvas range.
Slider.prototype.mouseMove = function (e) {
		if(!this.move) return ;//If the move mark is false, return directly var pos = _.getOffset(e);
		pos.x -= this.downX; //Subtract the initial mouse click position if(pos.x>580){
			return ;
		}
		this.update(pos);//move }
	//Update Slider.prototype.update=function(pos){
		//Change the coordinates of the slider and verification chart _.each(this.renderArr2,function(item){
			if(item){
				item.dx=pos.x;
			}
		});
		
		//Draw this.render();
	}

Mouse release event

  • The mouse moves the mark to false;
  • If you release the mouse before reaching the verification range, the slider and verification graph will return to the far left;
  • When the movement of the verification graph reaches a certain range, it means that the verification is passed;

After the verification is passed, a prompt will be displayed indicating that the verification is passed. The relevant content needs to be changed, such as clearing the missing blocks, changing the prompt text content, etc.

Slider.prototype.mouseUp=function(e){
		this.move=false;
		var pos = _.getOffset(e);
			pos.x -= this.downX;
		var validPos = this.validPos; //Verify the coordinates if(Math.abs(pos.x-validPos.x )<=10){ //Verification passed (the difference in x position can be within a certain range)
			console.log('pass')
			this.suc();
		}else{//Verification failed this.update({x:0});
		}
		this.render();
	}
	
	Slider.prototype.suc=function(){
		this.renderArr.splice(2,1);//Clear missing blocks this.block=null;
		//Clear the slider and verification chart this.renderArr2.length=0;
		//Change the color of the strip this.renderArr[1].fillStyle='#78C430';
		
		var text = this.renderArr[2];
		//Change of prompt content text.fillStyle='white';
		text.text="Verification successful";
	}

After success, it is as follows:

Download the complete code

This is the end of this article about JavaScript implementing drag slider puzzle verification (html5, canvas). For more relevant js implementation of drag slider puzzle verification content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JS implements drag slider verification
  • JavaScript Slider Validation Case
  • JavaScript to implement slider verification code
  • JavaScript to implement login slider verification
  • js canvas realizes slider verification
  • js implements sliding slider to verify login
  • Native JS encapsulation drag verification slider implementation code example
  • Implementation of JS reverse engineering of iQiyi slider encryption

<<:  MySQL Basic Tutorial Part 1 MySQL5.7.18 Installation and Connection Tutorial

>>:  How to deploy gitlab using Docker-compose

Recommend

WeChat applet learning wxs usage tutorial

What is wxs? wxs (WeiXin Script) is a scripting l...

Introduction to CSS3 color value RGBA and gradient color usage

Before CSS3, gradient images could only be used a...

In-depth understanding of this in JavaScript

In-depth understanding of this in Js JavaScript s...

MySQL database basic syntax and operation

MySQL database basic syntax DDL Operations Create...

6 interesting tips for setting CSS background images

Background-image is probably one of those CSS pro...

Detailed explanation of identifying files with the same content on Linux

Preface Sometimes file copies amount to a huge wa...

How to install Jenkins using Docker

Table of contents 1. Pull the image 2. Create a l...

Detailed steps to install web server using Apache httpd2.4.37 on centos8

Step 1: yum install httpd -y #Install httpd servi...

Native JS implements a very good-looking counter

Today I will share with you a good-looking counte...

Use js in html to get the local system time

Copy code The code is as follows: <div id=&quo...

How to view and clean up Docker container logs (tested and effective)

1. Problem The docker container logs caused the h...

Explanation of Dockerfile instructions and basic structure

Using Dockerfile allows users to create custom im...

Vue implements a movable floating button

This article example shares the specific code of ...

Detailed steps for configuring Tomcat server in IDEA 2020

The steps for configuring Tomcat in IDEA 2020 are...