JS验证码

Posted 王炜忠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS验证码相关的知识,希望对你有一定的参考价值。

1、引用jquery

2、html页面

 <div>
    <canvas id="canvas" style="cursor: pointer; height: 35px; width: 100px; top: 10px; position: relative;"></canvas>
        <input type="hidden"  id="yzmji" />
        <input type="button" id="a" />
    </div>
View Code

3、JS页面

<script>
    document.getElementById("a").onclick = function () {
        var b = $("#yzmji").val();
        alert(b);

    }

    var _picTxt = "";
    function randomNum(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
    }
    function randomColor(min, max) {
        var _r = randomNum(min, max);
        var _g = randomNum(min, max);
        var _b = randomNum(min, max);
        return "rgb(" + _r + "," + _g + "," + _b + ")";
    }
    document.getElementById("canvas").onclick = function (e) {
        e.preventDefault();
        drawPic();
        $("#yzmji").val(_picTxt.substr(_picTxt.length - 4, _picTxt.length - 1));
    };
    function drawPic() {
        var $canvas = document.getElementById("canvas");
        var _str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        var _num = 4;
        var _width = $canvas.width;
        var _height = $canvas.height;
        var ctx = $canvas.getContext("2d");
        ctx.textBaseline = "bottom";
        ctx.fillStyle = randomColor(180, 240);
        ctx.fillRect(0, 0, _width, _height);
        for (var i = 0; i < _num; i++) {
            var x = (_width - 10) / _num * i + 10;
            var y = randomNum(_height * 3 / 4, _height);
            var deg = randomNum(-45, 45);
            var txt = _str[randomNum(0, _str.length)];
            _picTxt += txt;
            ctx.fillStyle = randomColor(10, 100);
            ctx.font = randomNum(80, 90) + "px SimHei";
            ctx.translate(x, y);
            ctx.rotate(deg * Math.PI / 180);
            ctx.fillText(txt, 0, 0);
            ctx.rotate(-deg * Math.PI / 180);
            ctx.translate(-x, -y);
        }
        for (var i = 0; i < _num; i++) {
            ctx.strokeStyle = randomColor(90, 180);
            ctx.beginPath();
            ctx.moveTo(randomNum(0, _width), randomNum(0, _height));
            ctx.lineTo(randomNum(0, _width), randomNum(0, _height));
            ctx.stroke();
        }
        for (var i = 0; i < _num * 10; i++) {
            ctx.fillStyle = randomColor(0, 255);
            ctx.beginPath();
            ctx.arc(randomNum(0, _width), randomNum(0, _height), 1, 0, 2 * Math.PI);
            ctx.fill();
        }
        return _picTxt;
    }
    drawPic();
    $("#yzmji").val(_picTxt.substr(_picTxt.length - 4, _picTxt.length));




</script>
View Code

完!

以上是关于JS验证码的主要内容,如果未能解决你的问题,请参考以下文章

JSP 设计教师与学生不同登陆界面(带验证码)

js实现输入手机验证码后点击提交按钮验证手机输入的验证码和发送的验证码是不是一致

一百一十八:CMS系统之短信验证码加密和js代码混淆

jquery实现手机发送验证码的倒计时代码

git动态验证码

js短信验证码时间