let code;
function randomColor(min, max) { let r = randomNum(min, max); let g = randomNum(min, max); let b = randomNum(min, max); return "rgb(" + r + "," + g + "," + b + ")"; }
function randomNum(min, max) { return Math.floor(Math.random() * (max - min) + min); }
function createCode() { code = ""; let codeLength = 4; const checkCode = document.getElementById("myCanvas"); const codeChars = []; for (let i = 0; i < 26; i++) { if (i < 10) { codeChars.push(String.fromCharCode(i + 48)); } codeChars.push(String.fromCharCode(i + 97)); codeChars.push(String.fromCharCode(i + 65)); } for (let i = 0; i < codeLength; i++) { let charNum = Math.floor(Math.random() * 52); code += codeChars[charNum]; } if (checkCode) { drawVerify(checkCode, code); } }
function drawVerify(cEle, value) { const [ctx, width, height] = [cEle.getContext("2d"), cEle.width, cEle.height];
ctx.clearRect(0, 0, width, height); ctx.fillStyle = randomColor(180, 240); ctx.fillRect(0, 0, width, height); ctx.font = "30px Arial"; ctx.fillStyle = randomColor(50, 160); ctx.fillText(value, 20, 40); for (var i = 0; i < 2; i++) { ctx.strokeStyle = randomColor(40, 180); ctx.beginPath(); ctx.moveTo(randomNum(0, width), randomNum(0, height)); ctx.lineTo(randomNum(0, width), randomNum(0, height)); ctx.stroke(); } for (var i = 0; i < 30; i++) { ctx.fillStyle = randomColor(0, 255); ctx.beginPath(); ctx.arc(randomNum(0, width), randomNum(0, height), 1, 0, 2 * Math.PI); ctx.fill(); } }
function validateCode() { const [inputCode, warnToast] = [ document.getElementById("inputCode").value, document.getElementById("warnToast") ];
if (inputCode.length <= 0) { warnToast.innerHTML = "请输入验证码!"; } else if (inputCode.toUpperCase() != code.toUpperCase()) { warnToast.innerHTML = "验证码错误"; createCode(); } else { warnToast.innerHTML = "验证码正确!"; } }
|