zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

CheckCode.js 前端验证码插件

2023-03-14 22:36:29 时间

效果截图


20201230085659700.gif

插件使用方法


// 在html页面引入CheckCode.js
<script src="CheckCode.js"></script>
//定义
<script>
    let checkCode = new CheckCode({
        id:"code",      //容器的id值
        canvasId : "CheckCodeCanvas",    // canvas的id
        width:"100",        // canvas的宽度
        height:"30",       // canvas的高度
        type:"mix",         // 图形验证码默认类型mix:数字字母混合类型、number:纯数字、letter:纯字母
        });
    document.getElementById("button").onclick = function(){
        var res = checkCode .validate(document.getElementById("input").value);
        if(res){
            alert("验证正确");
        }else{
            alert("验证码错误");
        }
    }
</script>

CheckCode.js


/**
 * title -- 前端验证码插件一
 * author -- 三黄工作室
 * createTime -- 2020.12.28
 */

// 匿名函数 立即执行 避免冲突 提高性能
(function (window, document) {
    let N = 4; // 设置验证码长度
    function CheckCode(options){    //定义验证码类
        this.options = {
            id:"",      //容器的id值
            canvasId : "CheckCodeCanvas",    // canvas的id
            width:"100",        // canvas的default宽度
            height:"30",       // canvas的default高度
            type:"mix",         //图形验证码默认类型mix:数字字母混合类型、number:纯数字、letter:纯字母
            code:""
        }

        this.number = "1,2,3,4,5,6,7,8,9,0";
        this.letter = "q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";

        // 初始化传入参数,判断参数类型,如果是object类型则依次赋值,否则赋给id
        this.initOptions = () => {
            if(Object.prototype.toString.call(options) == "[object Object]")
                for(let i in options)
                    this.options[i] = options[i];
            else
                this.options.id = options;
        }

        this.initOptions();

        this._init();
        this.create();
        this.style();
    }

    CheckCode.prototype = {
        title : "前端验证码插件一",
        author : "三黄工作室",
        createTime : "2020.12.28",
        styleJson:{
            font:[],
            x:[],
            y:[],
            deg:[],
            time:0
        },

        // 初始化验证码
        _init : function(){
            let con = document.getElementById(this.options.id);
            let 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.create();
            }
        },

        // 生成验证码
        create : function(){

            this.options.code = '';
            let txtArr='';
            switch(this.options.type){
                case 'mix': txtArr = (this.number+','+this.letter).split(",");break;
                case 'number': txtArr = this.number.split(",");break;
                case 'letter': txtArr = this.letter.split(",");break;
            }

            for(let i=1;i<=N;++i)
                this.options.code += txtArr[getRandomNum(0,txtArr.length-1)];
            
        },

        // 生成画布样式数据
        style : async function(){
            
            this.styleJson.time=0;
            this.styleJson.font=[];
            this.styleJson.x=[];
            this.styleJson.y=[];
            this.styleJson.deg=[];
            for(let i=1;i<=N;++i){
                this.styleJson.font.push(getRandomNum(this.options.height/2, this.options.height) + 'px SimHei');  // 字大小
                this.styleJson.x.push(this.options.width / (N+1) * i);
                this.styleJson.y.push(this.options.height /1.2);
                this.styleJson.deg.push(getRandomNum(-30, 30));
            }

            while(1){
                this.draw();
                await sleep(20);
            }
            
        },

        // 循环生成画布
        draw : function(){
            let canvas = document.getElementById(this.options.canvasId);
            let ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, this.options.width, this.options.height);   //  清除已有画布内容

            // 背景
            ctx.fillStyle = '#000';
            ctx.fillRect(0, 0, this.options.width, this.options.height);

            ctx.fillStyle = '#fff';
            ctx.fillRect(this.styleJson.time, 0, 20, this.options.height);
            if(this.styleJson.time>=this.options.width) this.styleJson.time=0;
            this.styleJson.time+=2;

            for(let i=0;i<N;++i){
                ctx.font = this.styleJson.font[i];
                ctx.fillStyle = '#000';
                ctx.shadowColor = "rgba(0, 0, 0, 0.4)";
                /**设置旋转角度和坐标原点**/
                ctx.translate(this.styleJson.x[i], this.styleJson.y[i]);
                ctx.rotate(this.styleJson.deg[i] * Math.PI / 180);
                ctx.fillText(this.options.code[i], 0, 0);
                /**恢复旋转角度和坐标原点**/
                ctx.rotate(-this.styleJson.deg[i] * Math.PI / 180);
                ctx.translate(-this.styleJson.x[i], -this.styleJson.y[i]);
            }
        },

        /**验证验证码**/
        validate: function(code){
            if(code == this.options.code){
                return true;
            }else{
                this.create();
                return false;
            }
        }
        
    }

    let getRandomColor = () => {
        return  '#' + (function(color){
             return (color +=  '0123456789abcdef'[Math.floor(Math.random()*16)])    
             && (color.length == 6) ?  color : arguments.callee(color);    
        })('');
     }

     /**生成一个随机数**/
    let getRandomNum = (min, max) =>{
        return Math.floor(Math.random() * (max - min) + min);
    }

    function sleep(ms){//时间延迟函数
        return new Promise(resolve =>setTimeout(resolve,ms))
    }

    // 导出CheckCode类
    window.CheckCode = CheckCode;
    
})(window, document)

本插件的参考示例


如果需要本插件的示例,请扫描关注我的公众号,回复“前端验证码”即可。