Last active
October 16, 2022 02:45
-
-
Save jiaowochunge/d400f0572cc73bf82bdeee9e89f690db to your computer and use it in GitHub Desktop.
simple js captcha, front end validate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Captcha() { | |
const CharSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; | |
const canvas = document.createElement('canvas'); | |
canvas.width = 160; | |
canvas.height = 50; | |
const ctx = canvas.getContext("2d"); | |
function addCharToCanvas(ctx, char, index) { | |
const fontSize = 30, x = 10, y = 40; | |
ctx.font = `${fontSize}px Arial`; | |
// random translate, -5 ~ 5 | |
const rtx = Math.random() * 10 - 5 + index * 40; | |
const rty = Math.random() * 10 - 5; | |
ctx.translate(rtx, rty); | |
// random rotate, -20 ~ 20 degree | |
const rr = (Math.random() * 40 - 20) * Math.PI / 180; | |
ctx.rotate(rr); | |
// random scale, 0.8 ~ 1.2 | |
const rsx = Math.random() * 0.4 + 0.8; | |
const rsy = Math.random() * 0.4 + 0.8; | |
ctx.scale(rsx, rsy); | |
ctx.fillText(char, x, y); | |
ctx.resetTransform(); | |
} | |
let origin = ''; | |
for (let i = 0; i < 4; i++) { | |
const rc = CharSet.charAt(Math.floor(Math.random() * CharSet.length)); | |
addCharToCanvas(ctx, rc, i); | |
origin += rc; | |
} | |
// add random lines | |
const lineCount = Math.round(Math.random() * 2 + 2); | |
for (let j = 0; j < lineCount; j++) { | |
ctx.beginPath(); | |
const rx = Math.random() * canvas.width, ry = Math.random() * canvas.height; | |
ctx.moveTo(rx, ry); | |
const rx2 = Math.random() * canvas.width, ry2 = Math.random() * canvas.height; | |
ctx.lineTo(rx2, ry2); | |
ctx.stroke(); | |
} | |
function verify(code) { | |
return code.toLowerCase() === origin.toLowerCase(); | |
} | |
return [canvas.toDataURL('image/png', 0.1), verify]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment