随机字符串验证码

纯前端写算术验证码

效果

验证码实现步骤:

  • canvas画布
  • 生成随机100以内的简单整数四则运算
  • 随机颜色
  • 背景色(可固定色)
  • 噪音线设置
  • 绘制验证码

其他一些基础内容也包含其中,如点击验证码刷新、点击下一步验证等操作。

步骤实现:

本案例基于vue操作,UI使用element完成,

1. canvas画布

html

<!-- 输入框 -->
<input v-model="inputCode" placeholder="请输入右侧图案的值" />
<!-- canvas画布:验证码 -->
<canvas ref="checkCode" @click="getCode"></canvas>
<!-- 按钮 -->
<button @click="checkMe">下一步</button>

js

// 需要的数据
data() {
    return {
        inputCode: '',  // 输入的值
        checkCode: '',  // 图片验证码的值
        expressValue: '',  // 表达式的值
        // canvas各种设置
        cvs: {
            w: 100, // 给出默认宽度  宽度会在图片绘制时根据长度更改
            h: 40,  // 高 与input保持一致
            fontSize: 24,   // 字体大小
            str: '+-*',  // 符号生成范围
            line: 3 // 噪音线个数
        }
    }
}
2. 生成随机表达式
  • 写一个随机整数生成器,在各个环节都会用到
  • 生成随机字符串,长度是在data里面cvs中对应长度

// 随机整数生成器,范围[0, max)
rInt(max) {
    return Math.floor(Math.random() * 100000 % max);
},

// 生成随机表达式
rCode() {
    let a = this.rInt(100);
    let b = this.rInt(10);
    let op = this.cvs.str.charAt(this.rInt(this.cvs.str.length));
    // 表达式
    let code = `${a}${op}${b}=`;
    this.checkCode = code;
    // 表达式的值
    this.expressValue = eval(code.substr(0, code.length - 1));
    return code;
},
3. 生成随机颜色
  • rgba格式
  • a:透明度,取值为0.5-1

 // 生成随机颜色 rgba格式
rColor() {
    let a = ((Math.random()*5 + 5) / 10).toFixed(2);
    return `rgba(${this.rInt(256)}, ${this.rInt(256)}, ${this.rInt(256)}, ${a})`
},
4. 开始绘制
  • 方法接收一个dom对象
  • 判断浏览器对canvas支持程度
  • 取随机字表达式
  • 设置canvas宽高大小
  • 绘制

具体过程如下:

// 验证码图片绘制
drawCode(domCvs) {
    let _this = this;
    // 随机表达式
    let checkCode = this.rCode();
    // 宽设置
    this.cvs.w = 10 + this.cvs.fontSize * this.checkCode.length;

    // 判断是否支持canvas
    if (domCvs !== null && domCvs.getContext && domCvs.getContext('2d')) {
        // 设置显示区域大小
        domCvs.style.width = _this.cvs.w;
        // 设置画板宽高
        domCvs.setAttribute('width', _this.cvs.w);
        domCvs.setAttribute('height', _this.cvs.h);
        // 画笔
        let pen = domCvs.getContext('2d');
        // 背景: 颜色  区域
        pen.fillStyle = '#eee';
        pen.fillRect(0, 0, _this.cvs.w, _this.cvs.h);
        // 水平线位置
        pen.textBaseline = 'middle';   // top middle bottom
        // 内容
        for (let i = 0; i < _this.checkCode.length; i++) {
            pen.fillStyle = _this.rColor(); // 随机颜色
            pen.font = `bold ${_this.cvs.fontSize}px 微软雅黑`; // 字体设置
            // 字符绘制: (字符, X坐标, Y坐标)
            pen.fillText(checkCode.charAt(i), 10 + _this.cvs.fontSize * i, 17 + _this.rInt(10));
        }
        // 噪音线
        for (let i = 0; i < _this.cvs.line; i++) {
            // 起点
            pen.moveTo(_this.rInt(_this.cvs.w) / 2, _this.rInt(_this.cvs.h));
            // 终点
            pen.lineTo(_this.rInt(_this.cvs.w), _this.rInt(_this.cvs.h));
            // 颜色
            pen.strokeStyle = _this.rColor();
            // 粗细
            pen.lineWidth = '2';
            // 绘制
            pen.stroke();
        }

    } else {
        this.$message.error('不支持验证码格式,请升级或更换浏览器重试');
    }
},
5. 绑定canvas的dom元素

html

<canvas class="codeCanvas" ref="checkCode" @click="getCode"></canvas>

js:getCode方法

// vue的话可直接用$refs取值,不用vue的话可绑定id然后通过document处理
let domCvs = this.$refs.checkCode;
this.drawCode(domCvs);
6. 完成~
  • 在页面初始化的时候,也来一个验证码

  • 点击下一步, 验证datainputCodeexpressValue的值是否一样即可。注意,直接使用eval验证即可

  • 页面初始化

// 初始化先搞一个验证码~点击canvas的时候重新执行getCode()
mounted() {
    // 获取验证码图
    this.getCode();
}
  • 验证

checkMe() {
    // 空、 错误、 正确 三个判断
    if (this.inputCode) {
        if (eval(this.inputCode) === eval(this.expressValue)) {
            // 验证成功要做的事
            this.$message.success('验证成功');
        } else {
            // 验证码有误
            this.$message.warning('错误,请重新输入');
        }
    } else {
        // 输入为空
        this.$message.warning('请输入右侧结果');
    }
}

所有源码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>随机字符串验证码</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        * {
            box-sizing: border-box;
        }

        [v-cloak] {
            display: none;
        }


        .box-card {
            margin: 50px auto 0;
            width: 480px;
        }

        .codeCanvas{
            height: 40px;
            cursor: pointer;
        }

        .btnBox{
            margin-top: 50px;
            width: 100%;
            text-align: center;
        }
    </style>
</head>

<body>
    <div id="app" v-cloak>
        <el-card class="box-card">
            <!-- 输入组 -->
            <el-row :gutter="20">
                <el-col :span="14">
                    <div class="grid-content bg-purple">
                        <!-- 输入框 -->
                        <el-input v-model="inputCode" placeholder="请输入验证码,不区分大小写"></el-input>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="grid-content bg-purple">
                        <canvas class="codeCanvas" ref="checkCode" @click="getCode"></canvas>
                    </div>
                </el-col>
            </el-row>


            <div class="btnBox">
                <!-- 按钮 -->
                <el-button type="primary" round icon="el-icon-d-arrow-right" @click="checkMe">下一步</el-button>
            </div>

        </el-card>
    </div>


    <!-- js -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    inputCode: '',  // 输入的值
                    checkCode: '',  // 图片验证码的值
                    cvs: {
                        w: 100, // 给出默认宽度  宽度会在图片绘制时根据长度更改
                        h: 40,
                        fontSize: 24,   // 字体大小
                        str: '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM',  // 字符串生成范围
                        len: 4, // 字符串长度 
                        line: 3 // 噪音线个数
                    }
                }
            },
            methods: {
                // 随机整数生成器,范围[0, max)
                rInt(max) {
                    return Math.floor(Math.random() * 100000 % max);
                },
                // 生成随机字符串
                rCode() {
                    let code = '';
                    let len = this.cvs.len;
                    let strLen = this.cvs.str.length;
                    for(let i = 0; i < len; i ++) {
                        code += this.cvs.str.charAt(this.rInt(strLen));
                    }
                    this.checkCode = code;
                    return code;
                },
                // 生成随机颜色 rgba格式
                rColor() {
                    let a = ((Math.random()*5 + 5) / 10).toFixed(2);
                    return `rgba(${this.rInt(256)}, ${this.rInt(256)}, ${this.rInt(256)}, ${a})`
                },
                // 验证码图片绘制
                drawCode(domCvs) {
                    let _this = this;
                    // 随机字符串
                    let checkCode = this.rCode();
                    // 宽设置
                    this.cvs.w = 10 + this.cvs.fontSize * this.cvs.len;

                    // 判断是否支持canvas
                    if(domCvs !== null && domCvs.getContext && domCvs.getContext('2d')){
                        // 设置显示区域大小
                        domCvs.style.width = _this.cvs.w;
                        // 设置画板宽高
                        domCvs.setAttribute('width', _this.cvs.w);
                        domCvs.setAttribute('height', _this.cvs.h);
                        // 画笔
                        let pen = domCvs.getContext('2d');
                        // 背景: 颜色  区域
                        pen.fillStyle = '#eee';
                        pen.fillRect(0, 0, _this.cvs.w, _this.cvs.h);
                        // 水平线位置
                        pen.textBaseline = 'middle';   // top middle bottom
                        // 内容
                        for(let i = 0; i < _this.cvs.len; i ++) {
                            pen.fillStyle = _this.rColor(); // 随机颜色
                            pen.font = `bold ${_this.cvs.fontSize}px 微软雅黑`; // 字体设置
                            // 字符绘制: (字符, X坐标, Y坐标)
                            pen.fillText(checkCode.charAt(i), 10 + _this.cvs.fontSize * i, 17 + _this.rInt(10));   
                        }
                        // 噪音线
                        for(let i = 0; i < _this.cvs.line; i ++) {
                            // 起点
                            pen.moveTo(_this.rInt(_this.cvs.w) / 2, _this.rInt(_this.cvs.h));
                            // 终点
                            pen.lineTo(_this.rInt(_this.cvs.w), _this.rInt(_this.cvs.h));
                            // 颜色
                            pen.strokeStyle = _this.rColor();
                            // 粗细
                            pen.lineWidth = '2';
                            // 绘制
                            pen.stroke();
                        }

                    } else {
                        this.$message.error('不支持验证码格式,请升级或更换浏览器重试');
                    }
                },
                // 获取验证码
                getCode() {
                    let domCvs = this.$refs.checkCode;
                    this.drawCode(domCvs);
                },
                // 点击验证
                checkMe() {
                    // 空、 错误、 正确 三个判断
                    if(this.inputCode) {
                        if(this.inputCode.toLowerCase() === this.checkCode.toLowerCase()) {
                            // 验证成功要做的事
                            this.$message.success('验证成功');
                        } else {
                            // 验证码有误
                            this.$message.warning('验证码有误,请重新输入');
                        }
                    } else {
                        // 输入为空
                        this.$message.warning('请输入验证码');
                    }
                }

            },
            mounted() {
                // 获取验证码图
                this.getCode();
            }
        })
    </script>
</body>

</html>

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值