1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>前端生成验证码</title> </head> <body>
<canvas id="canvas" width="160" height="50"></canvas> </body> <script>
const getRandom = (min, max) => { return Math.floor(Math.random() * (max - min + 1)) + min }
const getColor = (min, max) => { let r = getRandom(min, max); let g = getRandom(min, max); let b = getRandom(min, max); return `rgb(${r},${g},${b}` }
const getVerificationCode = (selector, width, height) => {
let canvas = document.querySelector(selector); let ctx = canvas.getContext('2d'); ctx.fillStyle = getColor(215, 250); ctx.fillRect(0, 0, width, height);
let verificationCode = ''; for (let i = 0; i < 5; i++) { let ascii = getRandom(48, 122); if ((ascii > 57 && ascii < 65) || (ascii > 90 && ascii < 97)) { i--; continue; } const c = String.fromCharCode(ascii); verificationCode += c;
let fontSize = getRandom(height-(height*.4), height-(height*.1)); ctx.font = fontSize + 'px Simhei'; ctx.textBaseline = 'top'; ctx.fillStyle = getColor(80, 150); ctx.save(); ctx.translate(30 * i + 20, 10); let deg = getRandom(-30, 30); ctx.rotate(deg * Math.PI / 180); ctx.fillText(c, -10, -10); ctx.restore(); }
for (let j = 0; j < 5; j++) { ctx.beginPath(); ctx.moveTo(getRandom(0, width), getRandom(0, height)); ctx.lineTo(getRandom(0, width), getRandom(0, height)); ctx.strokeStyle = getColor(180, 230); ctx.closePath(); ctx.stroke(); }
for (let j = 0; j < 40; j++) { ctx.beginPath(); ctx.arc(getRandom(0, width), getRandom(0, height), 1, 0, 2 * Math.PI); ctx.closePath(); ctx.fillStyle = getColor(150, 200); ctx.fill(); } return verificationCode; }
let verificationCode = getVerificationCode('#canvas', 160, 60);
console.log("生成的验证码是:", verificationCode); </script> </html>
|