Capcha With Noise + refresh

by davidxmartins

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image CAPTCHA</title>
    <style>
        #captcha {
            border: 1px solid #ccc;
            width: 150px;
            height: 50px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <h1>Image CAPTCHA Demo</h1>
    <canvas id="captcha" width="150" height="50"></canvas>
    <input type="text" id="captchaInput" placeholder="Enter CAPTCHA">
    <button onclick="validateCaptcha()">Submit</button>
    <button onclick="refreshCaptcha()">Refresh CAPTCHA</button>
    <div id="result"></div>

    <script>
        const canvas = document.getElementById('captcha');
        const ctx = canvas.getContext('2d');
        let captchaText = generateCaptcha();

        function generateCaptcha() {
            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let result = '';
            for (let i = 0; i < 6; i++) {
                result += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            drawCaptcha(result);
            drawNoise(); // Add noise after drawing text
            return result;
        }

        function drawCaptcha(text) {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = '#f3f3f3';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            ctx.font = '30px Arial';
            ctx.fillStyle = '#000';

            for (let i = 0; i < text.length; i++) {
                const x = 10 + (i * 25) + Math.random() * 5; // Random x offset
                const y = 35 + Math.random() * 5; // Random y offset
                const angle = Math.random() * 0.2 - 0.1; // Random rotation
                ctx.save();
                ctx.translate(x, y);
                ctx.rotate(angle);
                ctx.fillText(text[i], 0, 0);
                ctx.restore();
         ...