API Reference

Complete documentation for ts-ascii-engine

Installation

npm install ts-ascii-engine

Import

// ES Modules (recommended)
import { AsciiGenerator, CharsetPreset } from 'ts-ascii-engine';

// CommonJS
const { AsciiGenerator, CharsetPreset } = require('ts-ascii-engine');

// TypeScript with types
import {
  AsciiGenerator,
  CharsetPreset,
  type AsciiConfig,
  type AsciiOutput
} from 'ts-ascii-engine';

Quick Start

Basic Image Conversion

import { AsciiGenerator, CharsetPreset } from 'ts-ascii-engine';

// Create generator
const generator = new AsciiGenerator({
  charset: CharsetPreset.BLOCK,
  width: 100,
  colored: true
});

// Convert image
const img = document.querySelector('img');
const result = generator.convertImage(img);

// Display as HTML
document.getElementById('output').innerHTML = result.html;

// Or use raw text
console.log(result.text);

AsciiGenerator

The main class for converting images, video, and text into ASCII art.

Constructor

constructor(config?: AsciiConfig)

Parameters:

  • config (optional) - Configuration object for the generator

Example:

const generator = new AsciiGenerator({
  charset: CharsetPreset.BLOCK,
  width: 100,
  colored: true,
  aspectRatio: 0.55
});

convertImage()

convertImage(source: ImageSource): AsciiOutput

Converts an image source to ASCII art.

Parameters:

  • source - Image, video, canvas, or ImageData to convert

Returns: AsciiOutput object with text, HTML, and metadata

Example:

// From image element
const img = document.querySelector('img');
const result = generator.convertImage(img);

// From video element
const video = document.querySelector('video');
const result = generator.convertImage(video);

// From canvas
const canvas = document.querySelector('canvas');
const result = generator.convertImage(canvas);

convertText()

convertText(text: string, options?: TextToAsciiOptions): AsciiOutput

Converts text into ASCII art using specified font.

Parameters:

  • text - String to convert
  • options (optional) - Font and rendering options

Returns: AsciiOutput object

Example:

// Simple text banner
const result = generator.convertText('HELLO');

// Custom font
const result = generator.convertText('ASCII', {
  font: 'Impact',
  fontSize: 80,
  fontWeight: 'bold'
});

updateConfig()

updateConfig(config: Partial<AsciiConfig>): void

Updates configuration dynamically without creating a new instance.

Parameters:

  • config - Partial configuration to update

Example:

// Update single property
generator.updateConfig({ width: 120 });

// Update multiple properties
generator.updateConfig({
  charset: CharsetPreset.BLOCK,
  colored: true,
  width: 100
});

getConfig()

getConfig(): Readonly<Required<AsciiConfig>>

Returns the current configuration (read-only copy).

Example:

const config = generator.getConfig();
console.log(`Current width: ${config.width}`);

Type Definitions

AsciiConfig

Configuration options for the ASCII generator.

interface AsciiConfig {
  charset?: CharsetPreset | string;
  inverted?: boolean;
  colored?: boolean;
  aspectRatio?: number;
  width?: number;
  height?: number;
  optimized?: boolean;
}
Property Type Default Description
charset CharsetPreset | string STANDARD Character set for rendering (dark to light)
inverted boolean false Invert brightness mapping
colored boolean false Include color information in output
aspectRatio number 0.55 Font aspect ratio correction (0.45-0.65)
width number 0 (auto) Target width in characters
height number 0 (auto) Target height in characters
optimized boolean true Enable performance optimizations

AsciiOutput

The result object returned by conversion methods.

interface AsciiOutput {
  text: string;
  html: string;
  characters: string[][];
  colors?: CharColor[][];
  metadata: AsciiMetadata;
}
Property Type Description
text string Raw ASCII text (newline-separated rows)
html string HTML string with optional color styling
characters string[][] 2D array of characters for programmatic access
colors CharColor[][] 2D array of color data (if colored: true)
metadata AsciiMetadata Processing information and statistics

Example:

const result = generator.convertImage(img);

// Display as text
console.log(result.text);

// Display as HTML
document.body.innerHTML = result.html;

// Access individual characters
const topLeftChar = result.characters[0][0];

// Access color data
if (result.colors) {
  const color = result.colors[0][0];
  console.log(`RGB: ${color.r}, ${color.g}, ${color.b}`);
}

CharsetPreset

Built-in character set presets.

enum CharsetPreset {
  BLOCK = 'BLOCK',
  STANDARD = 'STANDARD',
  MINIMAL = 'MINIMAL',
  EXTENDED = 'EXTENDED',
  CUSTOM = 'CUSTOM'
}
Preset Characters Count Best For
BLOCK ██▓▒░ 6 Modern look, high contrast
STANDARD @%#*+=-:. 10 Classic ASCII art
MINIMAL @+. 4 Simple, fast processing
EXTENDED 70+ chars 70+ Maximum detail

Custom Charset Example:

// Use custom characters (dark to light order)
const generator = new AsciiGenerator({
  charset: '█▓▒░ '
});

TextToAsciiOptions

Options for text-to-ASCII conversion.

interface TextToAsciiOptions {
  font?: string;
  fontSize?: number;
  fontWeight?: string | number;
  fontStyle?: string;
  color?: string;
  backgroundColor?: string;
  padding?: number;
}
Property Type Default Description
font string 'Arial' Font family to render text with
fontSize number 48 Font size in pixels (1-1000)
fontWeight string | number 'normal' Font weight
fontStyle string 'normal' Font style (normal, italic, oblique)
color string '#000000' Text color for rendering
backgroundColor string '#ffffff' Background color for rendering
padding number 10 Padding around text in pixels

Framework Integration

React Integration

import { AsciiGenerator, CharsetPreset } from 'ts-ascii-engine';
import { useEffect, useRef, useState } from 'react';

function AsciiImage({ src }) {
  const [html, setHtml] = useState('');
  const generatorRef = useRef(new AsciiGenerator({
    charset: CharsetPreset.BLOCK,
    width: 100,
    colored: true
  }));

  useEffect(() => {
    const img = new Image();
    img.onload = () => {
      const result = generatorRef.current.convertImage(img);
      setHtml(result.html);
    };
    img.src = src;
  }, [src]);

  return <div dangerouslySetInnerHTML={{ __html: html }} />;
}

// Usage
<AsciiImage src="/path/to/image.jpg" />

Vue 3 Integration

<template>
  <div v-html="asciiHtml"></div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { AsciiGenerator, CharsetPreset } from 'ts-ascii-engine';

const props = defineProps(['src']);
const asciiHtml = ref('');

const generator = new AsciiGenerator({
  charset: CharsetPreset.STANDARD,
  width: 80
});

watch(() => props.src, (src) => {
  const img = new Image();
  img.onload = () => {
    const result = generator.convertImage(img);
    asciiHtml.value = result.html;
  };
  img.src = src;
}, { immediate: true });
</script>

Angular Integration

// ascii.service.ts
import { Injectable } from '@angular/core';
import { AsciiGenerator, CharsetPreset } from 'ts-ascii-engine';

@Injectable({ providedIn: 'root' })
export class AsciiService {
  private generator = new AsciiGenerator({
    charset: CharsetPreset.STANDARD,
    width: 100
  });

  convertImage(source: HTMLImageElement) {
    return this.generator.convertImage(source);
  }

  updateConfig(config) {
    this.generator.updateConfig(config);
  }
}

Best Practices

Performance Tip: Reuse generator instances and update config instead of creating new instances.

Reuse Instances

// Good: Create once, update config
const generator = new AsciiGenerator();
generator.updateConfig({ width: 100 });
// ... later
generator.updateConfig({ width: 120 });

// Bad: Creating new instances
const gen1 = new AsciiGenerator({ width: 100 });
const gen2 = new AsciiGenerator({ width: 120 });

Choose Appropriate Width

// Mobile/thumbnails: 40-60
const mobileGen = new AsciiGenerator({ width: 50 });

// Desktop/detail: 80-120
const desktopGen = new AsciiGenerator({ width: 100 });

// High detail/print: 150-200
const printGen = new AsciiGenerator({ width: 180 });

Handle CORS Properly

// Correct: Set crossOrigin
const img = new Image();
img.crossOrigin = 'anonymous';
img.src = 'https://external-domain.com/image.jpg';