<head> <style> body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f4f4f4; } .captcha-container { text-align: center; border: 1px solid #ccc; padding: 20px; background-color: white; border-radius: 8px; } #captcha { margin: 10px 0; } .refresh-btn { padding: 10px 20px; cursor: pointer; background-color: #007BFF; color: white; border: none; border-radius: 5px; } .refresh-btn:hover { background-color: #0056b3; } </style> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div class="captcha-container"> <canvas id="captcha" width="200" height="80"></canvas> <button class="refresh-btn" id="refresh-btn">刷新验证码</button> </div> <script> function generateCaptcha() { const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let captcha = ''; for (let i = 0; i < 4; i++) { captcha += characters.charAt(Math.floor(Math.random() * characters.length)); } return captcha; } function drawCaptcha(captcha) { const canvas = document.getElementById('captcha'); const ctx = canvas.getContext('2d'); // 清空画布 ctx.clearRect(0, 0, canvas.width, canvas.height); // 设置背景色 ctx.fillStyle = '#e0e0e0'; // 淡灰色背景 ctx.fillRect(0, 0, canvas.width, canvas.height); // 绘制干扰线 for (let i = 0; i < 8; i++) { ctx.beginPath(); ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height); ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height); ctx.strokeStyle = 'rgba(0, 0, 0, 0.1)'; // 半透明干扰线 ctx.lineWidth = 1; ctx.stroke(); } // 绘制验证码 for (let i = 0; i < captcha.length; i++) { ctx.save(); ctx.translate(30 + i * 40, 50); // 设置字符位置 ctx.rotate((Math.random() - 0.5) * Math.PI / 6); // 随机旋转 ctx.font = `${30 + Math.random() * 10}px Arial`; // 随机字体大小 ctx.fillStyle = `hsl(${Math.random() * 360}, 100%, 50%)`; // 随机颜色 ctx.fillText(captcha[i], 0, 0); ctx.restore(); } } $(document).ready(function() { const captcha = generateCaptcha(); drawCaptcha(captcha); $('#refresh-btn').on('click', function() { const newCaptcha = generateCaptcha(); drawCaptcha(newCaptcha); }); }); </script> </body>
目录
前端验证码
分类:代码
时间:2024-11-29 11:30:52