内容字号: 默认 大号 超大号

段落设置:段首缩进取消段首缩进

字体设置:切换到宋体切换到微软雅黑

使用canvas生成的登录验证码js插件

发布:2018-08-31 浏览: 评论(

一个用canvas做的js验证码插件

!(function(window, document) {
	function GVerify(options) { //创建一个图形验证码对象,接收options对象为参数
		this.options = { //默认options参数值
			id: "", //容器Id
			canvasId: "verifyCanvas", //canvas的ID
			width: "100", //默认canvas宽度
			height: "30", //默认canvas高度
			type: "blend", //图形验证码默认类型blend:数字字母混合类型、number:纯数字、letter:纯字母
			code: "",
			interfereLine:false,//干扰线
			interfereLineNum:'',//干扰线数量//默认为codeNum的值
			noiseSpot:false, //干扰噪点
			noiseSpotNum:'',//干扰点数量//默认为width/codeNum
			codeNum:4,//验证码个数
			rotateMinDeg:-10,//旋转的最小角度
			rotateMaxDeg:10,//旋转的最大角度
			fontMinSize:'',//字体大小最小值 //默认为height值
			fontMaxSize:'' //字体大小最大值//默认为height值
		}
		
		if(Object.prototype.toString.call(options) == "[object Object]"){//判断传入参数类型
			for(var i in options) { //根据传入的参数,修改默认参数值
				this.options[i] = options[i];
			}
		}else{
			this.options.id = options;
		}
		
		this.options.numArr = "0,1,2,3,4,5,6,7,8,9".split(",");
		this.options.letterArr = getAllLetter();

		this._init();
		this.refresh();
	}

	GVerify.prototype = {
		/**版本号**/
		version: '1.0.0',
		
		/**初始化方法**/
		_init: function() {
			var con = document.getElementById(this.options.id);
			var canvas = document.createElement("canvas");
			this.options.width = con.offsetWidth > 0 ? con.offsetWidth : "100";
			this.options.height = con.offsetHeight > 0 ? con.offsetHeight : "30";
			canvas.id = this.options.canvasId;
			canvas.width = this.options.width;
			canvas.height = this.options.height;
			canvas.style.cursor = "pointer";
			canvas.innerHTML = "您的浏览器版本不支持canvas";
			con.appendChild(canvas);
			var parent = this;
			canvas.onclick = function(){
				parent.refresh();
			}
		},
		
		/**生成验证码**/
		refresh: function() {
			this.options.code = "";
			var canvas = document.getElementById(this.options.canvasId);
			if(canvas.getContext) {
				var ctx = canvas.getContext('2d');
			}else{
				return;
			}
			
			ctx.textBaseline = "middle";

			ctx.fillStyle = randomColor(180, 240);
			ctx.fillRect(0, 0, this.options.width, this.options.height);

			if(this.options.type == "blend") { //判断验证码类型
				var txtArr = this.options.numArr.concat(this.options.letterArr);
			} else if(this.options.type == "number") {
				var txtArr = this.options.numArr;
			} else {
				var txtArr = this.options.letterArr;
			}

			for(var i = 0; i <= this.options.codeNum-1; i++) {
				var txt = txtArr[randomNum(0, txtArr.length)];
				this.options.code += txt;
				ctx.font = randomNum((this.options.fontMinSize || this.options.height), (this.options.fontMaxSize || this.options.height)) + 'px SimHei'; //随机生成字体大小
				ctx.fillStyle = randomColor(50, 160); //随机生成字体颜色		
				ctx.shadowOffsetX = randomNum(-1, 1);
				ctx.shadowOffsetY = randomNum(-1, 1);
				ctx.shadowBlur = randomNum(-1, 1);
				ctx.shadowColor = "rgba(0, 0, 0, 0.3)";
				var x = this.options.width / this.options.codeNum * i;
				var y = this.options.height / 2;
				var deg = randomNum(this.options.rotateMinDeg, this.options.rotateMaxDeg);
				/**设置旋转角度和坐标原点**/
				ctx.translate(x, y);
				ctx.rotate(deg * Math.PI / 180);
				ctx.fillText(txt, 0, 0);
				/**恢复旋转角度和坐标原点**/
				ctx.rotate(-deg * Math.PI / 180);
				ctx.translate(-x, -y);
			}
			/**绘制干扰线**/
			if(this.options.interfereLine){
			    for(var i = 0; i <  (this.options.interfereLineNum || this.options.codeNum); i++) {
                                ctx.strokeStyle = randomColor(40, 180);
                                ctx.beginPath();
                                ctx.moveTo(randomNum(0, this.options.width), randomNum(0, this.options.height));
                                ctx.lineTo(randomNum(0, this.options.width), randomNum(0, this.options.height));
                                ctx.stroke();
                            }
			}
			
			/**绘制干扰点**/
			if(this.options.noiseSpot){
			    for(var i = 0; i < this.options.noiseSpotNum || (this.options.width/this.options.codeNum); i++) {
                                ctx.fillStyle = randomColor(0, 255);
                                ctx.beginPath();
                                ctx.arc(randomNum(0, this.options.width), randomNum(0, this.options.height), 1, 0, 2 * Math.PI);
                                ctx.fill();
                            }
			}
			
		},
		
		/**验证验证码**/
		validate: function(code){
			var code = code.toLowerCase();
			var v_code = this.options.code.toLowerCase();
			if(code == v_code){
				return true;
			}else{
				this.refresh();
				return false;
			}
		}
	}
	/**生成字母数组**/
	function getAllLetter() {
		var letterStr = "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";
		return letterStr.split(",");
	}
	/**生成一个随机数**/
	function randomNum(min, max) {
		return Math.floor(Math.random() * (max - min) + min);
	}
	/**生成一个随机色**/
	function randomColor(min, max) {
		var r = randomNum(min, max);
		var g = randomNum(min, max);
		var b = randomNum(min, max);
		return "rgb(" + r + "," + g + "," + b + ")";
	}
	window.GVerify = GVerify;
})(window, document);

下面是验证登录账号和密码的一个使用例子:


$(function(){
//新建一个验证码
    var verifyCode = new GVerify({
            id:"vdimgck",
            type:"blend",
            width:'50',
            height:'24'
    });
    $(".no-look-clear-js").on("click",function(){
        verifyCode.refresh();//刷新验证码方法
    })
    $(".login-button-js").on("click",function(){
        var self=$(this);
        if(self.hasClass("disabled")){
            return false;
        }
        var $errorUser=$(".error-user-js");
        var $verifyCode=$(".verify-code-js");
        var codeVal=$(".identify-code-js").val().toLowerCase();
        if(!verifyCode.validate(codeVal)){//验证验证码方法
            $verifyCode.show();
            $errorUser.hide();
            return false;
        }else{
            $verifyCode.hide();
        }
        var userName=$.trim($(".user-name-js").val());
        var userPwd=$.trim($(".user-password-js").val());
        if(userName!="" && userPwd!=""){
            self.addClass("disabled");
            $.ajax({
            	type:"post",
            	url:"",
            	data:{userName:userName,userPwd:userPwd},
            	success:function(res){
            	    if(res){
            	        $errorUser.hide();
            	        $(".login-form-js")[0].submit();
            	        window.location.href="administrator.html";
            	    }else{
            	        $errorUser.show();
            	    }
            	    self.removeClass('disabled');
            	},
            	error:function(msg){
            	    console.log(msg);
            	    self.removeClass('disabled');
            	}
            });
        }else{
            $errorUser.show();
            $verifyCode.hide();
            $(".user-name-js").focus()
        }
    })
})


前端新手交流群
欢迎加入web前端新手交流qq群:734802480

更多文章

相关文章

评论

发表评论愿您的每句评论,都能给大家的生活添色彩,带来共鸣,带来思索,带来快乐。


Copyright © 2014-2019 seozhijia.net 版权所有-粤ICP备13087626号-4