UNPKG

catchup-captcha

Version:

A simple captcha for using in front-end

90 lines (78 loc) 2.66 kB
class helper { letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; hexColor = "0123456789abcdef"; captcha = null; // canvas = document.createElement("canvas"); canvas = new OffscreenCanvas(0,0) context = this.canvas.getContext("2d"); options = { stringLength: 6, lineNoise: 25, dotNoise: 150, }; constructor(options) { this.options.stringLength = options.stringLength; this.options.lineNoise = options.lineNoise; this.options.dotNoise = options.dotNoise; } generateStringForCaptcha(length = 6) { let index = null; let captchaString = ""; for (let i = 0; i < length; i++) { index = Math.floor(Math.random() * (this.letters.length - 1)); captchaString += this.letters.charAt(index); } return captchaString; } colorGenerator() { let index = null; let color = "#"; for (let i = 0; i < 6; i++) { index = Math.floor(Math.random() * (this.hexColor.length - 1)); color += this.hexColor.charAt(index); } return color; } lineNoiseGenerator(length = 25) { for (let i = 0; i < length; i++) { this.context.beginPath(); this.context.moveTo( this.canvas.width * Math.random(), this.canvas.height * Math.random() ); this.context.lineTo( this.canvas.width * Math.random(), this.canvas.height * Math.random() ); this.context.strokeStyle = this.colorGenerator(); this.context.lineWidth = 2; this.context.stroke(); } } dotNoiseGenerator(length = 150) { for (let i = 0; i < length; i++) { this.context.fillStyle = this.colorGenerator(); this.context.fillRect( this.canvas.width * Math.random(), this.canvas.height * Math.random(), 5, 5 ); } } convertCanvasToImage() { let base64StringImage = this.canvas.toDataURL(); return base64StringImage; } prepareCanvas(){ this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); // this.canvas.style.border = "1px solid black"; // this.canvas.style.width = "150px"; // this.canvas.style.backgroundColor = this.colorGenerator(); this.context.font = "italic 75px Arial"; this.context.fillStyle = this.colorGenerator(); this.captcha = this.generateStringForCaptcha(); this.context.fillText(this.captcha, 0, 100); } } export default helper;