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)

本插件的参考示例


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

相关文章
|
14天前
|
前端开发 JavaScript 数据处理
前端新手指南:如何解决JavaScript导出CSV文件不完整的问题
【6月更文挑战第4天】在JavaScript中处理CSV文件时,需要特别注意一些特殊字符,例如逗号、双引号、换行符等。这些字符可能会影响CSV文件的解析,导致数据错乱。
49 0
|
11天前
|
前端开发 JavaScript 安全
高级前端开发需要知道的 25 个 JavaScript 单行代码
1. 不使用临时变量来交换变量的值 2. 对象解构,让数据访问更便捷 3. 浅克隆对象 4. 合并对象 5. 清理数组 6. 将 NodeList 转换为数组 7. 检查数组是否满足指定条件 8. 将文本复制到剪贴板 9. 删除数组重复项 10. 取两个数组的交集 11. 求数组元素的总和 12. 根据指定条件判断,是否给对象的属性赋值 13. 使用变量作为对象的键 14. 离线状态检查器 15. 离开页面弹出确认对话框 16. 对象数组,根据对象的某个key求对应值的总和 17. 将 url 问号后面的查询字符串转为对象 18. 将秒数转换为时间格式的字符串 19.
20 3
高级前端开发需要知道的 25 个 JavaScript 单行代码
|
14天前
|
JavaScript 前端开发 网络协议
前端JS发起的请求能暂停吗?
在讨论前端JS发起的请求是否能暂停时,需要明确两个概念:什么状态可以被认为是“暂停”?以及什么是JS发起的请求?
74 1
前端JS发起的请求能暂停吗?
|
1天前
|
前端开发 JavaScript 开发者
探索现代前端框架:从React到Vue.js
【6月更文挑战第26天】在数字时代的浪潮中,前端框架如同建筑的基石,支撑着互联网界面的创新与发展。本文将带领读者穿梭于React与Vue.js这两个最受欢迎的前端框架之间,揭示它们的核心特性、设计理念以及在实际开发中的应用差异。通过比较分析,我们将理解每个框架的优势和局限,并探索如何根据项目需求作出明智的选择。加入我们,一起深入前端技术的瑰丽世界,发现构建未来网络界面的无限可能。
|
5天前
|
设计模式 前端开发 JavaScript
关于写好前端JS代码的一些建议
关于写好前端JS代码的一些建议
17 2
|
10天前
|
传感器 前端开发 JavaScript
前端开发者必备的VS Code插件推荐
前端开发者必备的VS Code插件推荐
|
13天前
|
XML 前端开发 JavaScript
前端简介(HTML+CSS+JS)
前端简介(HTML+CSS+JS)
|
17天前
|
前端开发 JavaScript 安全
TypeScript作为一种静态类型的JavaScript超集,其强大的类型系统和面向对象编程特性为微前端架构的实现提供了有力的支持
【6月更文挑战第11天】微前端架构借助TypeScript提升开发效率和代码可靠性。 TypeScript提供类型安全,防止微前端间通信出错;智能提示和自动补全加速跨代码库开发;重构支持简化代码更新。通过定义公共接口确保一致性,用TypeScript编写微前端以保证质量。集成到构建流程确保顺利构建打包。在微前端场景中,TypeScript是强有力的语言选择。
30 2
|
1天前
|
前端开发 JavaScript 数据可视化
详尽分享表格的编辑插件editable.js
详尽分享表格的编辑插件editable.js
|
3天前
|
JavaScript 前端开发
【前端 - Vue】关于ESlint代码规范及格式化插件
【前端 - Vue】关于ESlint代码规范及格式化插件