canvas实现图形验证码

<!DOCTYPE html>
<html lang="en">

<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">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        canvas {
            margin: 50px;
        }
    </style>
</head>

<body>


    <canvas width="220" height="120"></canvas>
    <script>
        var canvas = document.getElementsByTagName("canvas")[0];
        var text = canvas.getContext("2d"),
            arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'];
        function draw() {
            text.strokeRect(0, 0, 120, 40);
            for (var i = 0; i < 4; i++) {
                var x = i * 20 + 20,
                    y = 20 + 10 * Math.random(),
                    index = Math.floor(Math.random() * 14);
                text.font = "bold 20px 微软雅黑";
                text.translate(x, y);
                var deg = Math.random() * 90 * Math.PI / 180;
                text.rotate(deg);//使画布旋转任意角度实现验证码不规则旋转
                text.fillText(arr[index], 0, 0);//填充文字
                text.rotate(-deg);
                text.translate(-x, -y);
                text.fillStyle = color();

            }
            for (var i = 0; i < 8; i++) {
                text.beginPath();
                text.moveTo(Math.random() * 120, Math.random() * 40);
                text.lineTo(Math.random() * 120, Math.random() * 40);
                text.strokeStyle = color();
                text.stroke();
            }
            for (var i = 0; i < 20; i++) {
                text.beginPath();
                var x = Math.random() * 120;
                var y = Math.random() * 40;
                text.moveTo(x, y);
                text.moveTo(x + 1, y + 1);
                text.strokeStyle = color();
                text.stroke();

            }

        } draw();
        canvas.onclick = function () {
            text.clearRect(0, 0, 120, 40)//清除画布
            draw();
        }

        //获取随机颜色
        function color() {
            var r = Math.floor(Math.random() * 255),
                g = Math.floor(Math.random() * 255),
                b = Math.floor(Math.random() * 255);
            return `rgb(${r},${g},${b})`;
        }


    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/dtbk123/article/details/90145281