Skip to content

Instantly share code, notes, and snippets.

@jiaowochunge
Last active October 16, 2022 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiaowochunge/d400f0572cc73bf82bdeee9e89f690db to your computer and use it in GitHub Desktop.
Save jiaowochunge/d400f0572cc73bf82bdeee9e89f690db to your computer and use it in GitHub Desktop.
simple js captcha, front end validate
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