Creates a new CaptchaGenerator instance with specified dimensions.
Initializes the generator with default settings and random text generation. All configuration methods can be chained after construction for fluent API usage.
Configuration options for the CAPTCHA generator
Height of the CAPTCHA image in pixels (default: 100)
Width of the CAPTCHA image in pixels (default: 300)
Gets the current CAPTCHA text that will be displayed in the image.
This property returns the text that users need to enter to solve the CAPTCHA. For array-based captchas with multiple text segments, it returns the concatenated result.
The complete CAPTCHA text string
const captcha = new CaptchaGenerator()
.setCaptcha({ text: 'HELLO' });
console.log(captcha.text); // Output: "HELLO"
Sets the dimensions of the CAPTCHA image.
This method allows you to customize the width and height of the generated CAPTCHA image. Larger dimensions provide more space for text and security features but result in larger file sizes.
Height of the CAPTCHA image in pixels
Width of the CAPTCHA image in pixels
The CaptchaGenerator instance for method chaining
Sets a background image for the CAPTCHA to increase visual complexity and security.
Background images make it significantly harder for OCR systems to automatically solve the CAPTCHA while maintaining human readability. The image will be scaled to fit the CAPTCHA dimensions.
Image source as file path, URL, or Buffer
The CaptchaGenerator instance for method chaining
const captcha = new CaptchaGenerator()
.setBackground('./assets/noise-pattern.jpg')
.setCaptcha({ opacity: 0.9 }); // Make text more visible over background
const captcha = new CaptchaGenerator()
.setBackground('https://example.com/background.png');
Configures the CAPTCHA text appearance and content.
This method allows extensive customization of the CAPTCHA text including font, size, colors, rotation, skewing, and the actual text content. Supports both single configuration objects and arrays for multi-styled text segments.
Single captcha configuration or array of configurations for multi-styled text
The CaptchaGenerator instance for method chaining
const captcha = new CaptchaGenerator()
.setCaptcha({
text: 'SECURE',
font: 'Arial',
size: 60,
color: '#2c3e50'
});
const captcha = new CaptchaGenerator()
.setCaptcha({
text: 'VERIFY',
size: 50,
rotate: 20, // Random rotation up to ±20 degrees
skew: true, // Apply random skewing
opacity: 0.8 // Semi-transparent text
});
const captcha = new CaptchaGenerator()
.setCaptcha({
text: 'RAINBOW',
size: 45,
colors: ['#e74c3c', '#f39c12', '#f1c40f', '#27ae60', '#3498db', '#9b59b6']
});
const captcha = new CaptchaGenerator()
.setCaptcha([
{ text: 'SEC', size: 50, color: '#e74c3c', font: 'Arial' },
{ text: 'URE', size: 45, color: '#27ae60', font: 'Times' }
]);
Configures trace lines that connect CAPTCHA characters for enhanced security.
Trace lines are drawn connecting the CAPTCHA characters, making it significantly harder for automated systems to segment and recognize individual characters while maintaining human readability.
Trace line appearance configuration
The CaptchaGenerator instance for method chaining
const captcha = new CaptchaGenerator()
.setCaptcha({ text: 'HELLO' })
.setTrace({ color: '#95a5a6', size: 3 });
const captcha = new CaptchaGenerator()
.setCaptcha({ text: 'VERIFY' })
.setTrace({
color: '#bdc3c7',
size: 2,
opacity: 0.6 // Semi-transparent trace
});
const captcha = new CaptchaGenerator()
.setCaptcha({ text: 'SECURE' })
.setTrace({
color: '#e74c3c',
size: 5,
opacity: 0.8
});
Configures decoy characters that add visual noise to prevent automated solving.
Decoy characters are randomly placed fake characters that confuse OCR systems while being distinguishable from the actual CAPTCHA text by humans through differences in opacity, size, or color.
Decoy characters configuration
The CaptchaGenerator instance for method chaining
const captcha = new CaptchaGenerator()
.setCaptcha({ text: 'HELLO' })
.setDecoy({
total: 30,
opacity: 0.3,
color: '#95a5a6'
});
const captcha = new CaptchaGenerator()
.setCaptcha({ text: 'VERIFY' })
.setDecoy({
total: 15,
size: 12,
opacity: 0.2,
font: 'Arial'
});
const captcha = new CaptchaGenerator()
.setCaptcha({ text: 'SECURE' })
.setDecoy({
total: 50,
size: 18,
opacity: 0.4,
color: '#7f8c8d'
});
Generates the final CAPTCHA image as a PNG buffer asynchronously.
This method renders all configured elements (background, decoys, text, traces) into a final PNG image buffer that can be saved to file or sent to clients. The generation process is asynchronous to handle background image loading.
Promise that resolves to a PNG image buffer
import fs from 'fs';
const captcha = new CaptchaGenerator()
.setCaptcha({ text: 'HELLO' });
const buffer = await captcha.generate();
fs.writeFileSync('captcha.png', buffer);
console.log('CAPTCHA text:', captcha.text);
import express from 'express';
app.get('/captcha', async (req, res) => {
const captcha = new CaptchaGenerator()
.setDimension(300, 100)
.setCaptcha({ characters: 6 });
const buffer = await captcha.generate();
// Store captcha.text in session for verification
req.session.captcha = captcha.text;
res.type('png').send(buffer);
});
const captcha = new CaptchaGenerator({ width: 400, height: 150 })
.setBackground('./noise-bg.jpg')
.setCaptcha({
text: 'SECURE',
size: 60,
colors: ['#e74c3c', '#3498db'],
rotate: 15
})
.setTrace({ color: '#95a5a6', size: 3 })
.setDecoy({ total: 40, opacity: 0.3 });
const buffer = await captcha.generate();
Generates the CAPTCHA image synchronously without async/await.
This method provides synchronous CAPTCHA generation for use cases where
async operations are not suitable. Note that background images set via
setBackground()
are ignored - use the background
parameter instead.
Additional options for synchronous generation
Optional
background?: ImagePre-loaded background image (use resolveImage()
to load)
PNG image buffer
const captcha = new CaptchaGenerator()
.setCaptcha({ text: 'SYNC' });
const buffer = captcha.generateSync();
fs.writeFileSync('captcha.png', buffer);
import { CaptchaGenerator, resolveImage } from 'captcha-canvas';
// Load background image first
const backgroundImage = await resolveImage('./background.jpg');
const captcha = new CaptchaGenerator()
.setCaptcha({ text: 'HELLO' });
// Generate synchronously with background
const buffer = captcha.generateSync({ background: backgroundImage });
fs.writeFileSync('captcha.png', buffer);
function createCaptchaSync() {
const captcha = new CaptchaGenerator()
.setDimension(250, 80)
.setCaptcha({ characters: 5, size: 35 })
.setTrace({ size: 2, opacity: 0.7 });
return {
buffer: captcha.generateSync(),
text: captcha.text
};
}
Note: Background images set via setBackground()
are not used in sync mode.
Use the background
parameter with pre-loaded images instead.
Advanced CAPTCHA generator class with fluent API for creating highly customizable CAPTCHAs.
This class provides a builder pattern interface for generating secure CAPTCHA images with extensive customization options including text styling, background images, trace lines, and decoy characters for enhanced security.
Example: Basic usage
Example: Advanced customization
Since
2.0.0