@snowflake-snss/captcha-generator-custom
Version:
An NPM package to generate captcha images
114 lines (97 loc) • 3.71 kB
HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test Canvas</title>
<canvas id="myCanvas" width="200" height="80" style="border:1px solid #005295;">
Your browser does not support the canvas element.
</canvas>
<canvas></canvas>
<script>
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
let height = 80;
const c = 50; // darkness factor - ensure only visible colors
const r = 255 - c - Math.round(Math.random() * (255-c));
const g = 255 - c - Math.round(Math.random() * (255-c));
const b = 255 - c - Math.round(Math.random() * (255-c));
this._color = `rgb(${r}, ${g}, ${b})`;
//backgoundColor
ctx.globalAlpha = 1;
ctx.fillStyle = "#FFFFFF";
ctx.beginPath();
ctx.fillRect(0, 0, 200, height);
ctx.save();
let scaling = height / 150;
console.warn('scaling:', scaling);
if (scaling > 1.3) scaling = 1.3;
//draw line
let countLine = 3;
ctx.strokeStyle = this._color;
ctx.lineWidth = 4 * scaling;
ctx.beginPath();
for (let i = 0; i < countLine; i++) {
ctx.moveTo(Math.random()*200, 0);
ctx.lineTo(Math.random()*200, 400);
}
ctx.stroke();
//draw circle
ctx.fillStyle = `rgb(${150}, ${0}, ${150})`;//color purple
ctx.lineWidth = 0;
ctx.beginPath();
ctx.arc(
Math.round(Math.random() * 360) + 20, // X coordinate
Math.round(Math.random() * 360) + 20, // Y coordinate
Math.round(Math.random() * (2 * scaling)) + 1, // Radius
0, // Start anglez
Math.PI * 2 // End angle
);
ctx.fill();
//text
ctx.fillStyle = '#000000';
// Set position for text
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.translate(0, height);
ctx.translate(
Math.round(Math.random() * 40 - 20) + 30,
-1 * Math.round(Math.random() * (height / 8) - height / 16) - height / 2 + height / 8
);
ctx.rotate(0.3 * (Math.random() - 0.5));
// Set text value and print it to canvas
ctx.beginPath();
let character = 'hello12';
let xCoord = 0;
for (const chr of character) {
const size = ((Math.random() - 0.5) * 40 + 70) * scaling;
const font = 'swift';//chr.match(/[a-z]/i) ? 'swift' : 'serif';
console.log('font',font);
ctx.font = `bold ${size}px ${font}`;
ctx.fillText(chr, xCoord, 0);
xCoord += ctx.measureText(chr).width;
}
// Draw foreground noise
let foregroundNoice = 3000;
ctx.restore();
for (let i = 0; i < foregroundNoice; i++) {
ctx.beginPath();
let color = "#";
while (color.length < 7) color += Math.round(Math.random() * 16).toString(16);
color += "a0";
ctx.fillStyle = color;
ctx.arc(
Math.round(Math.random() * 400), // X coordinate
Math.round(Math.random() * height), // Y coordinate
Math.random() * 2, // Radius
0, // Start angle
Math.PI * 2 // End angle
);
ctx.fill();
}
</script>
</head>
<body>
</body>
</html>