用canvas写了个验证码

2017-10-25 · xiejiahe

也没有什么技术难点,出于无聊才写的, 并没有什么luan用

效果

点击在线预览

代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge, chrome=1">
    <meta name="renderer" content="webkit">
    <title>Canvas VerifyCode</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .app {
            user-select: none;
        }
        .demo {
            position: fixed;
            top: 100px;
            left: 100px;
        }
        #demo {
            border: 1px solid #ccc;
            cursor: pointer;
        }
        a {
            text-decoration: none;
            color: #000;
            user-select: none;
        }
    </style>
</head>
<body>

<div class="app">
    <div class="demo">
        <canvas id="demo"></canvas>
        <a href="javascript:;" id="refresh">看不清</a>
        <p class="val"></p>
    </div>
</div>

<script>


class VerifyCode {

    constructor (obj) {
        if( new.target !== VerifyCode ) {
            throw new Error('必须通过new生成实例');
        }
        // canvas 对象
        this.el = document.querySelector(obj.el);
        // canvas 高度
        this.height = obj.height;
        // canvas 宽度
        this.width = obj.width;
        // 字体大小, String
        this.fontSize = obj.fontSize || '16px';
        // 字体颜色
        this.color = obj.color;
        // 背景颜色
        this.bgColor = obj.backgroundColor || '#fff';
        // 渲染个数
        this.number = obj.number || 4;
        // 上下文
        this.ctx = this.el.getContext('2d');
        // 生成随机数字符
        this.str = obj.str ||'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbn0123456789';
        this.init();
        this.update();
    }

    static version () {
        return 'v1.0.0';
    }
    // 更新画布
    update () {
        this.drawStr();
        this.drawLine();
        this.drawPoint();
    }
    // 初始化
    init () {
        this.el.width = this.width;
        this.el.height = this.height;
    }
    // 随机数从最小到最大范围
    rand (min = 0, max = 9999999) {
        var rand = Math.ceil(Math.random() * max);
        return rand < min ? min : rand;
    }
    // 画字符
    drawStr () {
        this.ctx.fillStyle = this.bgColor;
        this.ctx.fillRect(0, 0, this.width, this.height);
        var str = '';
        for(var i = 0; i < this.number; i++) {
            this.ctx.fillStyle = this.color || `#${(Math.floor(Math.random() * 0xFFFFFF)).toString(16)}`;
            this.ctx.font = `${this.fontSize} Microsoft Yahei`;
            var text = this.str[this.rand(0, this.str.length - 1)];
            str+= text;
            var textWidth = Math.ceil(this.ctx.measureText(text).width);
            var x = this.width / this.number * i + 5;
            this.ctx.fillText(text, x, 25);
            this.ctx.fill();
        }
        VerifyCode.val = str;
    }
    // 画线
    drawLine () {
        for(var i = 0; i < 5; i++) {
            this.ctx.beginPath();
            this.ctx.lineWidth = 1;
            this.ctx.strokeStyle = '#000';
            this.ctx.moveTo(this.rand(0, this.width), this.rand(0, this.width));
            this.ctx.lineTo(this.rand(0, this.height), this.rand(0, this.height));
            this.ctx.closePath();
            this.ctx.stroke();
        }
    }
    // 画点
    drawPoint () {
        for(var i = 0; i < 99; i++) {
            this.ctx.fillStyle = '#000';
            this.ctx.beginPath();
            this.ctx.arc(this.rand(0, this.width), this.rand(0, this.height), .5, 0, Math.PI * 2);
            this.ctx.closePath();
            this.ctx.fill();
        }
    }
}

        
var photo = new VerifyCode({
    // canvas 元素, 一个css选择器
    el: '#demo',
    // canvas 宽度
    width: 100,
    // canvas 高度
    height: 40,
    // 渲染字符个数,默认4个
    number: 4,
    // 字符字体大小,默认16px
    fontSize: '30px',
    // canvas画布背景色
    backgroundColor: '#fff'
});
document.querySelector('.demo .val').textContent = VerifyCode.val;
var update = () => {
    photo.update();
    document.querySelector('.demo .val').textContent = VerifyCode.val;
}
document.getElementById('refresh').onclick = update;
document.getElementById('demo').onclick = update;
</script>
</body>
</html>

获取验证码

VerifyCode.val

更新验证码

var photo = new VerifyCode({
    el: '#demo',
    width: 100,
    height: 40,
});
photo.update();
JavaScript
原创文章,转载请注明出处。