使用canvas做验证码

2021-09-14  本文已影响0人  升龙无涯

验证码效果:


验证码

封装验证码制作:

// 获取随机颜色
function getColor(){
    return `rgb(${Math.floor(Math.random()*255)},${Math.floor(Math.random()*256)},${Math.floor(Math.random()*256)})`
}
// 获取随机数
function getRandom(a,b=0){
    var max = a;
    var min = b;
    if(a<b){
        max = b;
        min = a;
    }
    return Math.floor(Math.random()*(max-min))+min
}
// 设置cookie
function setCookie(key,value,seconds,path="/"){
    var date = new Date()
    date.setTime(date.getTime()-8*3600*1000 + seconds*1000)
    document.cookie = `${key}=${value};expires=${date};path=${path}`
}
// 获取cookie
function getCookie(key,path="/"){
    var cookiesArr = document.cookie.split('; ')
    for(var i=0;i<cookiesArr.length;i++){
        var brr = cookiesArr[i].split('=')
        if(brr[0] === key){
            return brr[1]
        }
    }
}
// 设置验证码 - 参数为canvas标签的节点对象
function getCode(ele,num=4){
    // 定义工具箱
    var ctx = ele.getContext('2d')
    // 随机点
    // 获取画布宽和高
    var width = ctx.canvas.width
    var height = ctx.canvas.height
    // 设置线段宽度
    ctx.lineWidth = 2
    // 循环创建点
    for(var i=0;i<1000;i++){
        // 开启路径
        ctx.beginPath()
        // 设置随机点的开始位置
        var x = getRandom(width-2)
        var y = getRandom(height-2)
        // 画点 - 将画笔放到开始位置
        ctx.moveTo(x,y)
        // 将画笔移动到1px后
        ctx.lineTo(x+1,y+1)
        // 填充颜色
        ctx.strokeStyle = getColor()
        ctx.stroke()
    }
    // 随机线
    for(var i=0;i<20;i++){
        // 开启路径
        ctx.beginPath()
        // 设置随机的开始位置
        var x = getRandom(width-2)
        var y = getRandom(height-2)
        // 设置随机的宽和高
        var w = getRandom(width-x)
        var h = getRandom(height-y)
        // 将画笔放到开始位置
        ctx.moveTo(x,y)
        // 将画笔移动到 开始位置+随机宽
        ctx.lineTo(x+w,y+h)
        // 填充随机颜色
        ctx.strokeStyle = getColor()
        ctx.stroke()
    }
    // 随机字符
    // 字符容器
    var strContainer = 'abcdefghijkmnpqrstuvwxyz2345678ABCDEFGHJKLMNPQRSTUVWXYZ'
    // 设置文字大小
    ctx.font = width/5 + "px 微软雅黑"
    // 设置文字垂直对齐方式
    ctx.textBaseline = 'middle';
    // 验证码字符串
    var str = '';
    // 遍历生成字符放在画布中
    for(var i=0;i<num;i++){
        // 开启路径
        ctx.beginPath()
        // 描边文字颜色
        ctx.fillStyle = "#f00"
        // 随机字符
        var word = strContainer[getRandom(strContainer.length)]
        // 设置每个文字所处的区域大小
        var w = width / num;
        // 定义文字left和top
        var left = getRandom(i*w, (i+1)*w-width/5)
        var top = getRandom(height / 2 - 10, height / 2 + 10)
        // 写文字
        ctx.fillText(word, left, top);
        // 将所有字符存起来
        str += word
    }   
    // 将验证码字符串存在cookie中
    setCookie('code',str,10)
}
// 刷新验证码 - 参数为canvas标签的节点对象
function flush(ele){
    // 重新获取工具箱
    var ctx = ele.getContext('2d')
    // 随机点
    // 获取画布大小
    var width = ctx.canvas.width
    var height = ctx.canvas.height
    // 将画布中内容清空
    ctx.clearRect(0,0,width,height)
    // 重新生成验证码
    getCode(ele)
}

// 校验验证码 - 参数为被验证的字符串 - 返回布尔值
function verify(str){
    // 从cookie中获取验证码字符串
    var codeWord = getCookie('code').toLowerCase()
    // 对比
    if(str.toLowerCase() === codeWord){
        return true
    }else{
        return false;
    }
}

调用使用html结构:

<style>
    .code{
        border:1px solid #000;
    }
</style>
<input type="text" name="code"><button>校验</button>
<div class="box">
<canvas class="code" width=150 height=50></canvas>

调用代码:

// 获取当前要显示验证码的canvas标签
var code = document.querySelector('.code')
// 生成验证码
getCode(code,4)
// 点击刷新验证码
code.onclick = function(){
    // 重新生成验证码
    flush(code)
}
// 点击校验annuity
document.querySelector('button').onclick = function(){
    // 获取用户输入的验证码
    var word = document.querySelector('[name="code"]').value;
    // 调用验证函数进行验证
    var bool = verify(word)
    // 验证成功
    if(bool) alert("验证成功")
    // 验证失败
    else alert("验证失败")
}
上一篇 下一篇

猜你喜欢

热点阅读