ascii-art

repository·master·Indexed 20 days ago

https://github.com/khrome/ascii-art

A 100% JavaScript library for generating ASCII/ANSI images, Figlet fonts, tables, and graphs. It supports Node.js and the browser, featuring TrueColor (32-bit), Braille overlays, and a fluent chaining API for composing elements. The package includes a CLI for image conversion and text styling, and provides a compatibility layer for users migrating from Chalk.

Tokens
4.4K
Snippets
21
Records
23
Agent score
73%

What's inside ascii-art

  1. Compose multiple ASCII elements

    master

    You can combine different ASCII elements (fonts, images, tables, etc.) into a single composition using chainable functions:

    • .lines(): Combine elements into lines.
    • .overlay(): Overlay one element on another.
    • .border(): Add a border around the composition.
    • .strip(): Remove certain elements.
    • .join(): Join elements together.
  2. Call ascii-art methods using Callbacks, Promises, or Await

    master

    All chains in ascii-art support three asynchronous calling styles. For example, when using .font() to render text with a specific Figlet font:

    • Callback: Pass a callback function (err, rendered) => { ... }.
    • Promise: Use .then() and .catch().
    • Await: Use await art.font(...).completed() inside a try/catch block.
    // Callback
    art.font("Some Text", 'doom', (err, rendered) => {
        if (err) return console.error(err);
        console.log(rendered);
    });
    
    // Promise
    art.font("Some Text', 'doom')
       .then((rendered) => {
           console.log(rendered);
       })
       .catch((err) => {
           console.error(err);
       });
    
    // Await
    try {
        let rendered = await art.font("Some Text", 'doom').completed();
        console.log(rendered);
    } catch (err) {
        console.error(err);
    }
  3. Install ascii-art

    master

    Depending on your environment, install ascii-art using one of the following methods:

    • In Code (Node.js/Bundlers): npm install --save ascii-art
    • CLI (Global): npm install -g ascii-art or the beta npm install -g ascii-art-cl
    • Web (Web Components): npm install --save ascii-art-webcomponents
    npm install --save ascii-art
  4. Migrate from Chalk to ascii-art

    master

    If you are currently using chalk, you can switch to ascii-art without changing your existing syntax. Simply replace your import:

    // Instead of:
    // var chalk = require('chalk');
    
    // Use:
    var chalk = require('ascii-art/kaolin');

    This allows you to keep using the chalk API while benefiting from ascii-art's expanded capabilities.

    var chalk = require('ascii-art/kaolin');
  5. Use the AsciiArt chaining API

    master

    The AsciiArt object provides a fluent, chainable API to compose different ASCII art effects (fonts, images, tables, borders, etc.) into a single output. You can chain multiple operations together and then resolve the final result using .then() or by providing a callback to the final method in the chain.

    Available chainable methods include:

    • .font(text, fontName, style, callback): Renders text using a specific font.
    • .image(options, callback): Renders an image using the provided options.
    • .table(options, callback): Renders data in an ASCII table.
    • .graph(options, callback): Renders a graph.
    • .border(options, callback): Wraps the current result in a border.
    • .overlay(text, options, callback): Overlays new text onto the current result at specific x and y coordinates.
    • .style(text, styles, callback): Applies ANSI styles to the text.
    • .strip(options, callback): Removes ANSI codes from the current result.
    • .lines(start, stop, callback): Slices the current result to specific line ranges.
    • .join(text, callback): Appends raw text to the current result.
    • .artwork(options, callback): Appends artwork from a file.

    To use the chain, call the methods sequentially and end with .then(handler) to receive the final string in a Promise-like fashion.

    const AsciiArt = require('ascii-art');
    
    // Example: Font with a border and then a style applied
    AsciiArt.Font.newReturnContext({ text: 'Hello', font: 'standard' })
      .border({ l: '|', r: '|', t: '-', b: '-' })
      .then(result => {
        console.log(result);
      });
  6. Apply ANSI styles to text

    master

    Use art.style(text, style, reset) to add ANSI styles to a string.

    Available Styles:

    • italic
    • bold
    • underline
    • |framed|
    • |encircled|
    • overline
    • blink
    • inverse

    Available Colors: Colors default to 8-bit output. You can enable higher fidelity modes via options:

    • is256: Use 256-color mode (ansi256).
    • isTrueColor: Output direct RGB (32-bit) to the console.
    art.style("Some Text", 'green', true) // returns String
  7. Render text with Figlet fonts

    master

    Use art.font(text, fontName, reset) to render a string using a Figlet font. The library acts as a package manager for fonts, defaulting to a /Fonts directory.

    UTF Fonts: You can use system UTF fonts by prefixing the font name with u:. Supported names include:

    • default, script, script+bold, gothic, gothic+bold, serif+bold+italic, serif+bold, serif+italic, monospace, sansserif, sansserif+bold+italic, sansserif+bold, sansserif+italic, doublestrike.
    art.font("Some Text", 'doom', true) // returns String
  8. Generate tables and graphs

    master

    The library provides methods to render structured data:

    • Tables: art.table(data, callback) renders data into an ANSI-aware table. Supports various styles and handles column sizing based on ANSI string width.
    • Graphs: art.graph(data, callback) renders data as a graph (e.g., using braille characters).
    // Table
    art.table({}, cb);
    
    // Graph
    art.graph({}, cb);
  9. Convert images to ASCII art

    master

    Use art.image(options, callback) to convert an image into ASCII/Braille art.

    Key Image Options:

    • src: Path to the image.
    • rows / cols: Dimensions.
    • stipple: A color (e.g., "#000000") used for braille character overlays.
    • posterize: (Boolean) Uses stipple on top of colored backgrounds to retain detail.
    • lineart: (Boolean) Outputs lineart using block characters.
    • stipple (as boolean): Outputs lineart using braille characters.
    • blended: Uses posterize with both lineart and braille at relative thresholds.
    • threshold: (0-255) Controls detail level.
    art.image({
        src: "myImage.jpg",
        rows: 80,
        cols: 80,
        stipple: "#000000",
        posterize: true,
        threshold: 40
    }, cb);
  10. Configure image color modes and algorithms

    master

    When rendering images, you can control the color depth and the algorithm used to match image colors to the terminal palette.

    Color Modes:

    • 4-bit: Low color depth.
    • 8-bit: Standard 256-color (set via Color.is256 = true).
    • 32-bit: TrueColor/RGB (set via Color.isTrueColor = true).

    Color Distance Algorithms: Use the -C flag (CLI) or configuration to select an algorithm:

    • euclideanDistance, classic, ratioDistance, classicByValue, CIE76Difference, closestByIntensity, rankedChannel, simple, minDeviation, luminosity, saturation, hue, original.
    • You can merge algorithms using the + syntax (e.g., algorithm1+algorithm2).
    var art = require('ascii-art');
    var Color = require('ascii-art-ansi/colors');
    
    // For 8-bit color
    Color.is256 = true;
    art.image({ src: "image.jpg", alphabet: "solid" }, cb);
    
    // For 32-bit TrueColor
    Color.isTrueColor = true;
    art.image({ src: "image.jpg", alphabet: "solid" }, cb);
  11. Configure custom request implementations with AsciiArt.use()

    master

    Use AsciiArt.use(interfaceName, implementation) to inject custom logic for external dependencies like network requests.

    Supported interfaces:

    • 'request': Provides a custom implementation for AsciiArt.Image.useRequest and AsciiArt.Artwork.useRequest. This is useful if you want to use a specific HTTP client (like axios or node-fetch) instead of the default.
    • 'artwork': Replaces the AsciiArt.Artwork module entirely.
    const AsciiArt = require('ascii-art');
    
    // Example: Injecting a custom request handler
    AsciiArt.use('request', myCustomRequestLibrary);
  12. Generate ASCII tables with AsciiArt.table()

    master

    Use AsciiArt.table(options, callback) to render structured data as an ASCII table. This is a direct call to the AsciiArt.Table.create implementation.

    Options for the options object:

    • data: An array of objects representing the rows.
    • columns: Array of column headers (defaults to keys of the first data object).
    • width: The width of the table (defaults to terminal width or 80).
    • intersection: Style for intersection points.
    • horizontalBar: Style for horizontal bars.
    • verticalBar: Style for vertical bars.
    • dataStyle: Style for cell data.
    • headerStyle: Style for the header row.
    • bars: Style for bars (if applicable).
    • cellStyle: Style for cells.
    • borderColor: Style for the border.
    const AsciiArt = require('ascii-art');
    
    const data = [
      { name: 'Alice', age: 30 },
      { name: 'Bob', age: 25 }
    ];
    
    AsciiArt.table({
      data: data,
      headerStyle: 'bold'
    }, (err, text) => {
      console.log(text);
    });