CheckCode.js 前端验证码插件

简介: CheckCode.js 前端验证码插件

效果截图


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)

本插件的参考示例


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

相关文章
|
11月前
|
JSON 自然语言处理 前端开发
【01】对APP进行语言包功能开发-APP自动识别地区ip后分配对应的语言功能复杂吗?-成熟app项目语言包功能定制开发-前端以uniapp-基于vue.js后端以laravel基于php为例项目实战-优雅草卓伊凡
【01】对APP进行语言包功能开发-APP自动识别地区ip后分配对应的语言功能复杂吗?-成熟app项目语言包功能定制开发-前端以uniapp-基于vue.js后端以laravel基于php为例项目实战-优雅草卓伊凡
585 72
【01】对APP进行语言包功能开发-APP自动识别地区ip后分配对应的语言功能复杂吗?-成熟app项目语言包功能定制开发-前端以uniapp-基于vue.js后端以laravel基于php为例项目实战-优雅草卓伊凡
|
10月前
|
JavaScript 前端开发 API
|
10月前
|
前端开发 JavaScript 数据可视化
58K star!这个让网页动起来的JS库,前端工程师直呼真香!
Anime.js 是一款轻量级但功能强大的JavaScript动画引擎,它能够以最简单的方式为网页元素添加令人惊艳的动效。这个项目在GitHub上已经获得58,000+星标,被广泛应用于电商页面、数据可视化、游戏开发等场景。
387 8
|
10月前
|
JavaScript 前端开发 容器
|
10月前
|
JavaScript 前端开发
|
10月前
|
存储 JavaScript 前端开发
|
11月前
|
资源调度 JavaScript 前端开发
前端开发必备!Node.js 18.x LTS保姆级安装教程(附国内镜像源配置)
本文详细介绍了Node.js的安装与配置流程,涵盖环境准备、版本选择(推荐LTS版v18.x)、安装步骤(路径设置、组件选择)、环境验证(命令测试、镜像加速)及常见问题解决方法。同时推荐开发工具链,如VS Code、Yarn等,并提供常用全局包安装指南,帮助开发者快速搭建高效稳定的JavaScript开发环境。内容基于官方正版软件,确保合规性与安全性。
10675 23
|
10月前
|
移动开发 JavaScript 前端开发
|
10月前
|
存储 JavaScript 前端开发
|
10月前
|
JavaScript 前端开发