<!DOCTYPE html>
<html>
<body>
<h2>登录界面</h2>
<!-- form表示表单 -->
<form id="loginForm">
<label for="username">用户名:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">密码:</label><br>
<input type="password" id="password" name="password"><br>
<label for="captcha">验证码:</label><br>
<input type="text" id="captcha_input" name="captcha"><br>
<canvas id="captcha" width="100" height="50"></canvas><br> <!-- canvas表示图 -->
<input type="button" value="提交" onclick="submitForm()">
</form>
</body>
<script>
window.onload = function() {
generateCaptcha(); /* 方便用于再网页加载完毕后立刻执行的操作 */
};
function generateCaptcha() {
/* 36表示36进制的包含字符0-9,a-z
10进制0-9 16进制0-9,a-f
substring(2,8) 标志从第2个字符开始到第7个字符结束,就是6为随机生成码
*/
var captcha = Math.random().toString(36).substring(2, 8); // 生成一个随机验证码
var canvas = document.getElementById('captcha'); //可以获取'captcha'元素改变其内容
var ctx = canvas.getContext('2d'); //getContext()方法可返回一个用于在画布上绘图的环境
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除之前的验证码 '2d'表示二维
ctx.font = '30px Arial'; //font可以设置字体样式
//fillText()方法用于在画布上绘制填充的文本,文本默认为黑色context.fillText(text,x,y,maxWith)
//text指要写入的文本,x:此参数从何处开始文本的x坐标,y:此参数从何处结束文本的y坐标
ctx.fillText(captcha, 10, 35); // 在canvas上画出新的验证码
sessionStorage.setItem('captcha', captcha); // 将验证码存储在sessionStorage中,以便后续验证
}
function submitForm() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var captchaInput = document.getElementById('captcha_input').value;
var captcha = sessionStorage.getItem('captcha');
if (captchaInput === captcha) { // 如果输入的验证码和实际的验证码匹配
alert('登录成功!用户名:' + username);
} else {
alert('验证码错误!请重新输入。');
generateCaptcha(); // 如果验证码错误,重新生成一个新的验证码
}
}
</script>
</html>