<style> * { padding: 0; margin: 0; } #a { width: 100%; height: 200px; background-color: #F5F5F5; display: flex; align-items: center; justify-content: center; position: absolute; } input { width: 200px; height: 40px; border: none; outline: none; margin-right: 10px; border-radius: 10px; font-size: 20px; color: #758BBC; } canvas { background-color: azure; border-radius: 10px; } #b { width: 100px; height: 40px; border: 0.2px #CCCCCC solid; position: absolute; left: 46%; top: 140px; border-radius: 10px; color: red; font-size: 20px; display: flex; justify-content: center; align-items: center; user-select: none; } </style> <body> <!-- 主 --> <div id="a"> <!-- 验证框 --> <input type="text" placeholder="请输入"> <!-- canvas画布 --> <canvas style="width: 90px; height: 40px;" onclick="ak()"></canvas> <!-- 提交 --> <div id="b" onclick="fn()"> <span>提交</span> </div> </div> <script> // 获取到input的value let ma = document.getElementsByTagName("input")[0]; let mb = document.getElementsByTagName("canvas")[0]; let width = mb.width; let height = mb.height; let arrs = 0; // 创建个数组 let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]; // 封装一个函数(生成随机数) function fzs() { // 生成4个值 let arra = ''; for (let i = 0; i < 4; i++) { let index = nb(0, arr.length - 1); arra += arr[index]; } return arra; } // 循环判断验证码 function fn() { let maValue = ma.value; arras.toLowerCase(); maValue.toLowerCase(); if (maValue == '') { alert('没有输入值'); } if (maValue === arras) { alert("正确"); } else { alert("账号或密码错误"); } } // 画布 function fz() { // 调用随机数 let arra = fzs(); // 赋给全局变量的值 arras = arra; // 转化为2d绘图 let mbs = mb.getContext("2d"); // 背景颜色 mbs.fillStyle = "#fff"; // 绘制一个实心的矩形 mbs.fillRect(0, 0, 300, 150); // 循环样式 for (let i = 0; i < 4; i++) { // 调用随机颜色 mbs.fillStyle = qwe(0, 255); // 设置字体 粗细 大小 样式 mbs.font = "900 100px 宋体"; // 必须放在后面不然第一个无效果(必须加i*50 切换位置不然会叠加) mbs.fillText(arra[i], 50 + i * 50, 100); } /**绘制干扰线**/ for (let i = 0; i < 5; i++) { mbs.strokeStyle = nb(40, 180); mbs.beginPath(); mbs.moveTo(nb(0, width / 2), nb(0, height / 2)); mbs.lineTo(nb(0, width / 2), nb(0, height)); mbs.stroke(); } /**绘制干扰点**/ for (let i = 0; i < 50; i++) { mbs.fillStyle = nb(255); mbs.beginPath(); mbs.arc(nb(0, width), nb(0, height), 1, 0, 2 * Math.PI); mbs.fill(); } } // 随机颜色 function qwe(min, max) { let a = nb(min, max); let b = nb(min, max); let c = nb(min, max); return " rgb( " + a + "," + b + "," + c + " ) "; } // 调用画布 fz(); // 点击刷新 function ak() { fz(); } // 随机数范围 function nb(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min } </script>