Creates a new CaptchaGenerator instance with optional initial dimensions.
Initial configuration options for canvas dimensions
// Create with default dimensions (100x300)
const captcha = new CaptchaGenerator();
// Create with custom dimensions
const captcha = new CaptchaGenerator({ height: 200, width: 500 });
Gets the current captcha text that should be used for verification.
This property returns the text that the user needs to enter to pass the captcha challenge. The text is automatically generated when the captcha is created or can be set manually using the setCaptcha method.
The captcha text string
const captcha = new CaptchaGenerator();
console.log('User should enter:', captcha.text); // e.g., "A3X9K2"
// With custom text
captcha.setCaptcha({ text: 'HELLO' });
console.log('User should enter:', captcha.text); // "HELLO"
Sets the canvas dimensions for the captcha image.
The dimensions affect the overall size of the generated captcha image and should be chosen based on your application's requirements. Larger dimensions provide more space for text and visual effects but may impact performance.
Canvas height in pixels (recommended: 100-300)
Canvas width in pixels (recommended: 200-600)
The CaptchaGenerator instance for method chaining
const captcha = new CaptchaGenerator()
.setDimension(150, 400) // 150px height, 400px width
.setCaptcha({ size: 60 });
// Method chaining allows fluent configuration
const buffer = await captcha.generate();
Sets a background image for the captcha to increase visual complexity and security.
Background images make it significantly harder for OCR systems to accurately read the captcha text. The image will be automatically resized to fit the canvas dimensions. Supported formats include JPEG, PNG, GIF, and other formats supported by the canvas library.
Background image as a Buffer or file path string
The CaptchaGenerator instance for method chaining
import fs from 'fs';
const backgroundBuffer = fs.readFileSync('./background.jpg');
const captcha = new CaptchaGenerator()
.setDimension(200, 400)
.setBackground(backgroundBuffer)
.setCaptcha({ color: 'white', opacity: 0.9 });
const captcha = new CaptchaGenerator()
.setBackground('./assets/background.png')
.setCaptcha({ color: 'yellow', size: 50 });
Configures the captcha text appearance and behavior.
This method accepts either a single options object for uniform styling or an array of options for segmented styling where different parts of the text can have different appearances. This is the core method for customizing how your captcha looks.
Single options object or array of options for segmented styling
The CaptchaGenerator instance for method chaining
const captcha = new CaptchaGenerator()
.setCaptcha({
text: 'HELLO', // Custom text (auto-generated if not provided)
color: 'blue', // Text color
size: 60, // Font size in pixels
font: 'Arial', // Font family
rotate: 10, // Max rotation angle in degrees
skew: true, // Enable text skewing
opacity: 0.8 // Text opacity (0-1)
});
const captcha = new CaptchaGenerator()
.setCaptcha({
characters: 6,
colors: ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4'],
size: 50,
rotate: 15
});
const captcha = new CaptchaGenerator()
.setCaptcha([
{ text: 'SEC', color: '#e74c3c', size: 60, start: 0, end: 3 },
{ text: 'URE', color: '#3498db', size: 50, start: 3, end: 6 }
]);
console.log(captcha.text); // "SECURE"
const captcha = new CaptchaGenerator()
.setCaptcha({
characters: 8, // Generate 8 random characters
size: 45,
colors: ['red', 'blue', 'green']
});
console.log(captcha.text); // e.g., "A7X9M2K5"
Configures trace lines that connect the captcha characters.
Trace lines are drawn between character positions to add visual complexity and make it harder for automated systems to isolate individual characters. These lines significantly improve the security of your captcha by creating visual noise that confuses OCR systems while remaining readable to humans.
Configuration options for trace lines
The CaptchaGenerator instance for method chaining
const captcha = new CaptchaGenerator()
.setCaptcha({ size: 60 })
.setTrace({
color: 'red', // Line color
size: 3, // Line width in pixels
opacity: 0.8 // Line opacity (0-1)
});
const captcha = new CaptchaGenerator()
.setCaptcha({ color: 'blue', size: 50 })
.setTrace({
color: 'lightblue',
size: 2,
opacity: 0.5 // Semi-transparent for subtle effect
});
const captcha = new CaptchaGenerator()
.setCaptcha({ color: '#32cf7e', size: 55 })
.setTrace({
color: '#32cf7e', // Same color as text
size: 4,
opacity: 0.7
});
Configures decoy characters that are scattered across the captcha background.
Decoy characters are random characters placed throughout the captcha image to confuse OCR systems and automated solvers. They appear as background noise and make it significantly harder for bots to identify the actual captcha text. The number of decoy characters is automatically calculated based on canvas size.
Configuration options for decoy characters
The CaptchaGenerator instance for method chaining
const captcha = new CaptchaGenerator()
.setCaptcha({ size: 60, color: 'black' })
.setDecoy({
color: 'gray', // Decoy text color
font: 'Arial', // Font family for decoys
size: 20, // Font size for decoys
opacity: 0.5 // Opacity (0-1)
});
const captcha = new CaptchaGenerator()
.setCaptcha({ size: 50, color: 'blue' })
.setDecoy({
color: 'lightgray',
size: 15, // Smaller than main text
opacity: 0.3 // Very subtle
});
const captcha = new CaptchaGenerator()
.setCaptcha({ size: 55, color: 'darkblue' })
.setDecoy({
color: 'blue',
size: 25,
opacity: 0.6 // More visible for higher security
});
Generates the captcha image asynchronously and returns it as a PNG buffer.
This method creates the final captcha image by rendering all configured elements (text, trace lines, decoy characters, background) onto a canvas. The method is asynchronous to handle background image loading if a background is set.
Promise that resolves to a PNG image buffer
const captcha = new CaptchaGenerator()
.setDimension(150, 400)
.setCaptcha({ size: 60 });
const buffer = await captcha.generate();
// Save to file
import fs from 'fs';
fs.writeFileSync('captcha.png', buffer);
// Get the text for verification
console.log('Captcha text:', captcha.text);
app.get('/captcha', async (req, res) => {
const captcha = new CaptchaGenerator()
.setDimension(150, 400)
.setCaptcha({ size: 60 });
const buffer = await captcha.generate();
res.setHeader('Content-Type', 'image/png');
res.send(buffer);
});
import fs from 'fs';
const backgroundBuffer = fs.readFileSync('./background.jpg');
const captcha = new CaptchaGenerator()
.setBackground(backgroundBuffer)
.setCaptcha({ color: 'white', size: 50 });
const buffer = await captcha.generate();
Generates the captcha image synchronously and returns it as a PNG buffer.
This method creates the captcha image without using async/await, making it suitable for synchronous workflows. If you need to use a background image, you must pre-load it using the canvas library's loadImage function and pass it in the options.
Optional configuration for synchronous generation
Optional
background?: ImagePre-loaded background image (use loadImage from canvas)
PNG image buffer
const captcha = new CaptchaGenerator()
.setDimension(150, 400)
.setCaptcha({ size: 60, color: 'blue' });
const buffer = captcha.generateSync();
// Save to file
import fs from 'fs';
fs.writeFileSync('captcha.png', buffer);
console.log('Captcha text:', captcha.text);
import { loadImage } from 'canvas';
// Pre-load the background image
const backgroundImage = await loadImage('./background.jpg');
const captcha = new CaptchaGenerator()
.setDimension(200, 400)
.setCaptcha({ color: 'white', size: 50 });
// Generate synchronously with pre-loaded background
const buffer = captcha.generateSync({ background: backgroundImage });
// Synchronous - faster for simple captchas without backgrounds
const buffer1 = captcha.generateSync();
// Asynchronous - required for background images from file/URL
const buffer2 = await captcha.generate();
A powerful and flexible CAPTCHA generator that creates secure, customizable CAPTCHA images.
The CaptchaGenerator class provides a fluent API for creating highly customized CAPTCHA images with features like custom fonts, colors, rotation, skewing, trace lines, decoy characters, and background images. It's designed to be both easy to use for simple cases and highly configurable for advanced security requirements.
Example: Basic Usage
Example: Advanced Configuration
Example: Segmented Text Styling
Example: With Background Image