JavaScript实现图片验证码

Captcha.js

/* Captcha.js v1.0.0 | This code is licensed under the GNU GPL License (GNU). */
!function(t,i){function o(t){if(this.options={id:"",canvasId:"verifyCanvas",width:"100",height:"30",type:"blend",code:""},"[object Object]"==Object.prototype.toString.call(t))for(var i in t)this.options[i]=t[i];else this.options.id=t;this.options.numArr="0,1,2,3,4,5,6,7,8,9".split(","),this.options.letterArr="a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".split(","),this._init(),this.refresh()}function s(t,i){return Math.floor(Math.random()*(i-t)+t)}function e(t,i){return"rgb("+s(t,i)+","+s(t,i)+","+s(t,i)+")"}o.prototype={version:"1.0.0",_init:function(){var t=i.getElementById(this.options.id),o=i.createElement("canvas");this.options.width=t.offsetWidth>0?t.offsetWidth:"100",this.options.height=t.offsetHeight>0?t.offsetHeight:"30",o.id=this.options.canvasId,o.width=this.options.width,o.height=this.options.height,o.style.cursor="pointer",o.innerHTML="Your browser doesn't support canvas",t.appendChild(o);var s=this;o.onclick=function(){s.refresh()}},refresh:function(){this.options.code="";var t=i.getElementById(this.options.canvasId);if(t.getContext){var o=t.getContext("2d");if(o.textBaseline="middle",o.fillStyle=e(180,240),o.fillRect(0,0,this.options.width,this.options.height),"blend"==this.options.type)var n=this.options.numArr.concat(this.options.letterArr);else n="number"==this.options.type?this.options.numArr:this.options.letterArr;for(var h=1;h<=4;h++){var r=n[s(0,n.length)];this.options.code+=r,o.font=s(this.options.height/2,this.options.height)+"px monospace",o.fillStyle=e(50,160),o.shadowOffsetX=s(-3,3),o.shadowOffsetY=s(-3,3),o.shadowBlur=s(-3,3),o.shadowColor="rgba(0, 0, 0, 0.3)";var a=this.options.width/5*h,p=this.options.height/2,l=s(-30,30);o.translate(a,p),o.rotate(l*Math.PI/180),o.fillText(r,0,0),o.rotate(-l*Math.PI/180),o.translate(-a,-p)}for(h=0;h<4;h++)o.strokeStyle=e(40,180),o.beginPath(),o.moveTo(s(0,this.options.width),s(0,this.options.height)),o.lineTo(s(0,this.options.width),s(0,this.options.height)),o.stroke();for(h=0;h<this.options.width/4;h++)o.fillStyle=e(0,255),o.beginPath(),o.arc(s(0,this.options.width),s(0,this.options.height),1,0,2*Math.PI),o.fill()}},validate:function(t){t=t.toLowerCase();var i=this.options.code.toLowerCase();return console.log(i),t==i||(this.refresh(),!1)}},t.Captcha=o}(window,document);

(其实这玩意是我自己写的)

测试用的html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>图形验证码</title>
	</head>
	<style>
		#app{
			margin-top: 160px;
			width: 500px;
			height: 300px;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			border: 2px solid pink;
		}
		#my_body{
			width: 200px;
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
		#code_input{
			width: 120px;
			height: 20px;
			line-height: 20px;
		}
		#code_input:focus {
			outline: 0;
		}
		#my_button{
			width: 50px;
			height: 24px;
		}
		#v_container{
			margin-bottom: 50px;
			width: 200px;
			height: 50px;
		}
	</style>
	<body>
		<div id="app">
			<div id="v_container" ></div>
			<div id="my_body">
				<input type="text" id="code_input" value="" placeholder="请输入验证码"/>
				<button id="my_button">验证</button>
			</div>
		</div>
	</body>
	<script src="/src/code/js/Captcha/v1.0.0/code.js"></script>
	<script>
		var verifyCode = new Captcha("v_container");
 
		document.getElementById("my_button").onclick = function(){
			var res = verifyCode.validate(document.getElementById("code_input").value);
			if(res){
				alert("验证正确");
			}else{
				alert("验证码错误");
			}
		}
	</script>
</html>

效果
效果图

### 使用 JavaScript 实现图片验证码生成与验证 #### 图片验证码生成原理 为了提高安全性并防止自动化程序破解,通常会在图片验证码中加入干扰因素如线条或噪点。通过 `canvas` API 可以轻松绘制这些图形元素。 ```html <canvas id="captchaCanvas"></canvas> <button onclick="generateCaptcha()">刷新</button> <input type="text" id="userInput"/> <button onclick="verifyCaptcha()">提交</button> <p id="resultMessage"></p> ``` #### 创建验证码逻辑 定义一个名为 `generateCaptcha` 的函数负责生成新的验证码字符串,并将其显示在 canvas 上: ```javascript function generateCaptcha() { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let captchaText = ''; // 随机选取四位字符作为验证码 for (let i=0; i<4; ++i){ captchaText += chars.charAt(Math.floor(Math.random()*chars.length)); } document.getElementById('captchaCanvas').innerHTML = ''; // 清除旧内容 drawOnCanvas(captchaText); } ``` 此段代码会从给定字符集中随机抽取四个字母组成一个新的验证码串[^3]。 #### 绘制验证码到 Canvas 中 接下来编写辅助方法 `drawOnCanvas`, 它接受刚才产生的验证码文本参数,在 HTML5 `<canvas>` 元素内渲染出来: ```javascript function drawOnCanvas(text) { var canvas = document.getElementById("captchaCanvas"); if (!canvas.getContext) {return;} var ctx = canvas.getContext("2d"); // 设置画布大小 canvas.width = 120; canvas.height = 40; // 填充白色背景 ctx.fillStyle = "#ffffff"; ctx.fillRect(0, 0, canvas.width, canvas.height); // 添加一些干扰线 for(var i=0;i<4;i++){ ctx.strokeStyle = randomColor(); ctx.beginPath(); ctx.moveTo(randomNumber(canvas.width), randomNumber(canvas.height)); ctx.lineTo(randomNumber(canvas.width), randomNumber(canvas.height)); ctx.stroke(); } // 将验证码文字写入图像 ctx.font = "bold 24px Arial"; ctx.textAlign = "center"; ctx.fillStyle = '#000'; text.split('').forEach((char, index)=>{ ctx.fillText(char, 30 * (index + 1), Math.random() * 10 + 25); }); } // 辅助工具函数 function randomNumber(max){ return Math.floor(Math.random()*max);} function randomColor(){ return '#' + ('00000' + ((Math.random()*(1<<24))|0).toString(16)).slice(-6);} ``` 这段脚本不仅展示了如何把文本绘制成可视化的形式,还加入了额外的视觉混淆措施来增强难度. #### 用户输入校验流程 当用户尝试提交表单时,调用另一个叫作 `verifyCaptcha()` 方法来进行匹配检验: ```javascript function verifyCaptcha(){ var userInput = document.getElementById('userInput').value.toUpperCase().trim(); // 获取当前显示的真实验证码值(假设存储于全局变量) if(userInput === CAPTCHA_VALUE){ alert('验证成功!'); document.getElementById('resultMessage').innerText='验证成功!'; }else{ alert('错误的验证码'); document.getElementById('resultMessage').innerText='验证失败,请重试.'; } } ``` 这里假定了有一个叫做 `CAPTCHA_VALUE` 的全局变量保存着最新一次生成的有效验证码供比较使用[^2].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值