前端canvas动态验证码实现

  <canvas id="cancasCode" width="100" height="40" @click="initCode"></canvas>
 // 生成一个随机数
    const randomNum = (min: number, max: number) => {
        return Math.floor(Math.random() * (max - min) + min)
    }
    // 生成一个随机的颜色
    const randomColor = (min: number, max: number) => {
        const r = randomNum(min, max)
        const g = randomNum(min, max)
        const b = randomNum(min, max)
        return 'rgb(' + r + ',' + g + ',' + b + ')'
    }
    //canvas图片刷新
    const initCode = () => {
        const len = 4
        const codeList: [] = []
        const chars: string = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789'
        const charsLen: number = chars.length
        for (let i = 0; i < len; i++) {
            codeList.push(chars.charAt(Math.floor(Math.random() * charsLen)))
        }
        const identifyCode = codeList.join('')
        console.log(identifyCode)
        form.sureCode = identifyCode
        //绘制图片
        const canvas: HTMLElement | null | any = document.getElementById('cancasCode')
        //画布
        const ctx = canvas.getContext('2d')
        ctx.textBaseline = 'bottom'
        //随机背景色
        ctx.fillStyle = randomColor(0, 255)
        //绘制矩形的长框(
        //    x	矩形左上角的 x 坐标。
        //    y	矩形左上角的 y 坐标。
        //    width	矩形的宽度,以像素计。
        //    height	矩形的高度,以像素计。
        //   )
        ctx.fillRect(0, 0, 100, 40)
        //绘制文字
        for (let i = 0; i < identifyCode.length; i++) {
            //文字颜色
            ctx.fillStyle = randomColor(0, 255)
            // 文字大小
            ctx.font = randomNum(12, 30) + 'px SimHei'
            const x = (i + 1) * (100 / (identifyCode.length + 1))
            const y = randomNum(30, 35)
            var deg = randomNum(-45, 45)
            //修改坐标原点与角度
            ctx.translate(x, y)
            ctx.rotate(deg * (Math.PI / 180))
            ctx.fillText(identifyCode[i], 0, 0)
            //恢复坐标原点
            ctx.rotate(-deg * (Math.PI / 180))
            ctx.translate(-x, -y)
        }
    }

源码地址 本人源码地址分享

猜你喜欢

转载自blog.csdn.net/weixin_48164217/article/details/120311230
今日推荐