canvas生成验证码

绘制验证码

/*生成画布:
    count:干扰线数量,
    text:验证码文本(可以前端自己生成,),
    fontSize:字体大小,
    width:画布宽度px,
    height:画布高度px,
*/
const initCanvas = (count, text, fontSize, width, height) => {
    let myCanvas = document.querySelector("#myCanvas")
    let ctx = myCanvas.getContext('2d')
    drawLine(ctx, count, width, height)
    drawTxt(ctx, text, fontSize, width, height)
}
/*绘制干扰线:
    ctx:画笔
    count:干扰线数量
    width:画布宽度px,
    height:画布高度px,
*/
const drawLine = (ctx, count, width, height) => {
    for (let i = 0; i < count; i++) {
        ctx.strokeStyle = randomHexColor();//颜色
        ctx.beginPath();
        ctx.moveTo(
            randomNum(0, width), randomNum(0, height)
        );
        ctx.lineTo(
            randomNum(0, width), randomNum(0, height)
        );
        ctx.stroke()
    }
}
/*绘制验证码:
    ctx:画笔,
    text:验证码文本,
    size:字体大小,
    width:画布宽度px,
    height:画布高度px,
*/
const drawTxt = (ctx, text, size, width, height) => {
    let fontLimit = Math.floor((width - size) / text.length) //每一个字体的位置宽度范围
    Array.from(text).forEach((char, i, arr) => {
        ctx.fillStyle = randomHexColor() //随机生成字体颜色
        ctx.font = `${size}px Arial`;
        let x1 = fontLimit * i
        let x2 = (width - size) - (arr.length - i - 1) * fontLimit
        let x = randomNum(x1, x2)
        let y = randomNum(size, height)
        ctx.fillText(char, x, y);
    })
}
// 随机生成验证码(参数:验证码位数)
const randomCode = (count) => {
    const txt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'//长度为62
    let text = ''
    for (let i = 0; i < count; i++) {
        text += txt.charAt(randomNum(0, 62))
    }
    // 可以在此处将生成的验证码存到页面
    return text
}
// 随机生成16进制颜色
const randomHexColor = () => {
    let color = `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`
    if (color !== "0xffffff") {
        return color
    }
}
// 随机生成数字
const randomNum = (min, max) => {
    return Math.floor(Math.random() * (max - min) + min)
}

使用时直接调用 initCanvas(count, text, fontSize, width, height),传入相关参数即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值