欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

canvas验证码

程序员文章站 2022-02-27 11:44:03
...
//captcha.js
//验证码

// 接收外界传入的参数对象params{},更改验证码的样式
function Captcha(params = {}) {
    let middleParams = Object.assign({
        lineWidth: 0.5,
        lineNum: 5,
        dotR: 1,
        dotNum: 50,
        preGroundColor: [10, 80],
        backGroundColor: [150, 250],
        fontSize: 30,
        fontFamily: ['Georgia', '微软雅黑', 'Helvetica', 'Arial'],
        fontStyle: 'fill',
        content: 'acdefhijkmnpwxyABCDEFGHJKMNPQWXY12345789',
        length: 4
    }, params);
    Object.keys(middleParams).forEach(item => {
        this[item] = middleParams[item]
    });
    this.canvas = null;
    this.paint = null
};
Captcha.prototype.getRandom = function (...arr) {
    arr.sort((a, b) => a - b);
    return Math.floor(Math.random() * (arr[1] - arr[0]) + arr[0])
};
Captcha.prototype.getColor = function (arr) {
    let colors = new Array(3).fill('');
    colors = colors.map(item => this.getRandom(...arr));
    return colors
};
Captcha.prototype.getText = function () {
    let length = this.content.length;
    let str = '';
    for (let i = 0; i < this.length; i++) {
        str += this.content[this.getRandom(0, length)]
    }
    return str
};
Captcha.prototype.line = function () {
    for (let i = 0; i < this.lineNum; i++) {
        let x = this.getRandom(0, this.canvas.width);
        let y = this.getRandom(0, this.canvas.height);
        let endX = this.getRandom(0, this.canvas.width);
        let endY = this.getRandom(0, this.canvas.height);
        this.paint.beginPath();
        this.paint.lineWidth = this.lineWidth;
        let colors = this.getColor(this.preGroundColor);
        this.paint.strokeStyle = 'rgba(' + colors[0] + ',' + colors[1] + ',' + colors[2] + ',' + '0.8)';
        this.paint.moveTo(x, y);
        this.paint.lineTo(endX, endY);
        this.paint.closePath();
        this.paint.stroke()
    }
};
Captcha.prototype.circle = function () {
    for (let i = 0; i < this.dotNum; i++) {
        let x = this.getRandom(0, this.canvas.width);
        let y = this.getRandom(0, this.canvas.height);
        this.paint.beginPath();
        this.paint.arc(x, y, this.dotR, 0, Math.PI * 2, false);
        this.paint.closePath();
        let colors = this.getColor(this.preGroundColor);
        this.paint.fillStyle = 'rgba(' + colors[0] + ',' + colors[1] + ',' + colors[2] + ',' + '0.8)';
        this.paint.fill()
    }
};
Captcha.prototype.font = function () {
    let str = this.getText();
    this.callback(str);
    this.paint.font = this.fontSize + 'px ' + this.fontFamily[this.getRandom(0, this.fontFamily.length)];
    this.paint.textBaseline = 'middle';
    let fontStyle = this.fontStyle + 'Text';
    let colorStyle = this.fontStyle + 'Style';
    for (let i = 0; i < this.length; i++) {
        let fontWidth = this.paint.measureText(str[i]).width;
        let x = this.getRandom(this.canvas.width / this.length * i + 0.2 * fontWidth, (this.canvas.width / this.length) * i + 0.5 * fontWidth);
        let deg = this.getRandom(-6, 6);
        let colors = this.getColor(this.preGroundColor);
        this.paint[colorStyle] = 'rgba(' + colors[0] + ',' + colors[1] + ',' + colors[2] + ',' + '0.8)';
        this.paint.save();
        this.paint.rotate(deg * Math.PI / 180);
        this.paint[fontStyle](str[i], x, this.canvas.height / 2);
        this.paint.restore()
    }
};
Captcha.prototype.draw = function (dom, callback = function () {}) {
    if (!this.paint) {
        this.canvas = dom;
        if (!this.canvas) return;
        else this.paint = this.canvas.getContext('2d');
        this.callback = callback;
        this.canvas.onclick = () => {
            this.drawAgain()
        }
    }
    let colors = this.getColor(this.backGroundColor);
    this.paint.fillStyle = 'rgba(' + colors[0] + ',' + colors[1] + ',' + colors[2] + ',' + '0.8)';
    this.paint.fillRect(0, 0, this.canvas.width, this.canvas.height);
    this.circle();
    this.line();
    this.font()
};
Captcha.prototype.clear = function () {
    this.paint.clearRect(0, 0, this.canvas.width, this.canvas.height)
};
//刷新画布方法
Captcha.prototype.drawAgain = function () {
    this.clear();
    this.draw(this.callbak)
};

if (typeof module !== 'undefined' && !module.nodeType && module.exports) {
    module.exports = Captcha
}
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>不传值</h2>
<canvas width="140" height="40" id="captcha1"></canvas>
<input id="input" type="text" name="" id="" >
<button onclick="check()">check</button>
<br>
<!-- <h2>传值</h2>
<canvas width="240" height="90" id="captcha2"></canvas> -->
</body>
<script src="./captcha.js"></script>
<script>
    /*不传值,统一走默认值*/
    var checkNumber = null;
    let captcha1 = new Captcha();
    captcha1.draw(document.querySelector('#captcha1'), r => {
        console.log(r, '验证码1');
        checkNumber = r.toLowerCase()
    });
    
    var input = document.querySelector("#input")
    function check(){
        if(input.value === checkNumber){
            alert('验证通过')
        }else if(input.value !== checkNumber){
            alert('验证码错误')
            captcha1.drawAgain()
        }
        console.log(input.value)
        console.log(checkNumber)


    }

    /*传值,参数配置值,选择性配置*/
    // let captcha2 = new Captcha({
    //     lineWidth: 1,   //线条宽度
    //     lineNum: 6,       //线条数量
    //     dotR: 2,          //点的半径
    //     dotNum: 25,       //点的数量
    //     preGroundColor: [10, 80],    //前景色区间
    //     backGroundColor: [150, 250], //背景色区间
    //     fontSize: 30,           //字体大小
    //     fontFamily: ['Georgia', '微软雅黑', 'Helvetica', 'Arial'],  //字体类型
    //     fontStyle: 'stroke',      //字体绘制方法,有fill和stroke
    //     content: '一个验证码abcdefghijklmnopqrstuvw生成的插件使用的是canvas显示',  //验证码内容
    //     length: 6    //验证码长度
    // }); // 传值
    // captcha2.draw(document.querySelector('#captcha2'), r => {
    //     console.log(r, '验证码2');
    // });
</script>
</html>

相关标签: 笔记