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

import { CaptchaGenerator } from 'captcha-canvas';

const captcha = new CaptchaGenerator()
.setDimension(150, 400)
.setCaptcha({ size: 60, color: 'blue' });

const buffer = await captcha.generate();
console.log('Captcha text:', captcha.text);

Example: Advanced Configuration

const captcha = new CaptchaGenerator({ height: 200, width: 500 })
.setCaptcha({
text: 'SECURE',
colors: ['#ff6b6b', '#4ecdc4', '#45b7d1'],
font: 'Arial',
size: 70,
rotate: 15,
skew: true
})
.setTrace({
color: '#ff6b6b',
size: 4,
opacity: 0.7
})
.setDecoy({
opacity: 0.4,
size: 25
});

const buffer = await captcha.generate();

Example: Segmented Text Styling

const captcha = new CaptchaGenerator()
.setDimension(150, 450)
.setCaptcha([
{ text: 'SEC', color: '#e74c3c', size: 60, start: 0, end: 3 },
{ text: 'URE', color: '#3498db', size: 50, start: 3, end: 6 }
]);

console.log('Text:', captcha.text); // "SECURE"

Example: With Background Image

import fs from 'fs';

const backgroundBuffer = fs.readFileSync('./background.jpg');
const captcha = new CaptchaGenerator()
.setDimension(200, 400)
.setBackground(backgroundBuffer)
.setCaptcha({ color: 'white', size: 50, opacity: 0.9 });

const buffer = await captcha.generate();

Constructors

  • Creates a new CaptchaGenerator instance with optional initial dimensions.

    Parameters

    Returns default

    Example

    // Create with default dimensions (100x300)
    const captcha = new CaptchaGenerator();

    // Create with custom dimensions
    const captcha = new CaptchaGenerator({ height: 200, width: 500 });

Accessors

  • get text(): string
  • 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.

    Returns string

    The captcha text string

    Example

    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"

Methods

  • 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.

    Parameters

    • height: number

      Canvas height in pixels (recommended: 100-300)

    • width: number

      Canvas width in pixels (recommended: 200-600)

    Returns this

    The CaptchaGenerator instance for method chaining

    Example

    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.

    Parameters

    • image: string | Buffer

      Background image as a Buffer or file path string

    Returns this

    The CaptchaGenerator instance for method chaining

    Example: Using Buffer

    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 });

    Example: Using File Path

    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.

    Parameters

    Returns this

    The CaptchaGenerator instance for method chaining

    Example: Basic Text Styling

    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)
    });

    Example: Multiple Colors

    const captcha = new CaptchaGenerator()
    .setCaptcha({
    characters: 6,
    colors: ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4'],
    size: 50,
    rotate: 15
    });

    Example: Segmented Styling

    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"

    Example: Auto-generated Text

    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.

    Parameters

    Returns this

    The CaptchaGenerator instance for method chaining

    Example: Basic Trace Lines

    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)
    });

    Example: Subtle Trace Lines

    const captcha = new CaptchaGenerator()
    .setCaptcha({ color: 'blue', size: 50 })
    .setTrace({
    color: 'lightblue',
    size: 2,
    opacity: 0.5 // Semi-transparent for subtle effect
    });

    Example: Matching Text Color

    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.

    Parameters

    Returns this

    The CaptchaGenerator instance for method chaining

    Example: Basic Decoy Characters

    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)
    });

    Example: Subtle Decoys

    const captcha = new CaptchaGenerator()
    .setCaptcha({ size: 50, color: 'blue' })
    .setDecoy({
    color: 'lightgray',
    size: 15, // Smaller than main text
    opacity: 0.3 // Very subtle
    });

    Example: High Security Decoys

    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.

    Returns Promise<Buffer>

    Promise that resolves to a PNG image buffer

    Example: Basic Generation

    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);

    Example: Express.js Response

    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);
    });

    Example: With Background Image

    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.

    Parameters

    • options: {
          background?: Image;
      } = {}

      Optional configuration for synchronous generation

      • Optional background?: Image

        Pre-loaded background image (use loadImage from canvas)

    Returns Buffer

    PNG image buffer

    Example: Basic Synchronous Generation

    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);

    Example: With Pre-loaded Background

    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 });

    Example: Performance Comparison

    // Synchronous - faster for simple captchas without backgrounds
    const buffer1 = captcha.generateSync();

    // Asynchronous - required for background images from file/URL
    const buffer2 = await captcha.generate();