spritesmith

repository·master·Indexed 21 days ago

https://github.com/twolfson/spritesmith

A utility for converting multiple individual images into a single spritesheet and a corresponding JSON coordinate map. Version 3.5.1 supports a high-level API via Spritesmith.run() and a class-based constructor for streaming output. It is engine-agnostic, supporting engines like pixelsmith, phantomjssmith, canvassmith, and gmsmith, and provides various layout algorithms such as binary-tree, top-down, left-right, and diagonal.

Tokens
4.4K
Snippets
12
Records
18
Agent score
26%

What's inside spritesmith

  1. Overview of spritesmith functionality

    master

    spritesmith converts a collection of images into a single spritesheet and a coordinate map.

    • Spritesheet: A single image containing all input images.
    • Coordinate Map: A JSON object mapping each input filename to its position and dimensions within the spritesheet:
    {
      "/path/to/image.png": {
        "x": 0,
        "y": 0,
        "width": 32,
        "height": 32
      }
    }
  2. Configure spritesheet layout algorithms

    master

    You can control how images are packed using the algorithm option. Spritesmith uses the layout library to provide several packing strategies:

    • binary-tree: (Default) Packs images as efficiently as possible.
    • top-down: Packs images in a top-down fashion.
    • left-right: Packs images from left to right.
    • diagonal: Packs images diagonally.
    • alt-diagonal: An alternative diagonal packing.

    Use algorithmOpts to pass specific settings to these algorithms (e.g., disabling sorting in top-down).

  3. How the Spritesmith API changed in v3.0.0

    master

    In version 3.0.0, the API was updated to support streaming outputs. This involved moving to a class-based constructor and separating the image creation phase from the processing phase.

    To maintain compatibility with older codebases, Spritesmith.run was introduced as a static method that provides the same behavior as the pre-3.0.0 function.

  4. Choose a Spritesmith engine

    master

    Engines determine how images are interpreted and exported. You can specify an engine via params.engine and its settings via params.engineOpts.

    EngineRequirementsBest For
    pixelsmithNone (Default)Standard Node-based usage.
    phantomjssmithphantomjs installed on PATHCross-platform compatibility and all image formats.
    canvassmithCairo and node-gypHigh performance (100+ sprites), but UNIX only.
    gmsmithGraphics Magick or Image MagickConfiguring image quality and specific format support.
  5. Use a custom layout algorithm

    master

    You can specify a custom layout algorithm by passing the algorithm key in the options object to Spritesmith.run(). This allows you to control how images are arranged within the spritesheet (e.g., using 'alt-diagonal').

    var fs = require('fs');
    var Spritesmith = require('spritesmith');
    
    // Generate our spritesheet
    Spritesmith.run({
      src: [
        __dirname + '/fork.png',
        __dirname + '/github.png',
        __dirname + '/twitter.png'
      ],
      algorithm: 'alt-diagonal'
    }, function handleResult (err, result) {
      if (err) {
        throw err;
      }
    
      // Output the image
      fs.writeFileSync(__dirname + '/alt-diagonal.png', result.image);
      result.coordinates, result.properties; // Coordinates and properties
    });
  6. Use a custom engine

    master

    Spritesmith allows you to swap the underlying engine used for image processing. To use a custom engine, install the engine package (e.g., canvassmith) and pass the required module to the engine key in the Spritesmith.run() options object.

    // Inside package.json
    {
        "dependencies": {
            "canvassmith": "~0.2.4"
        }
    }
    // In our script
    var fs = require('fs');
    var Spritesmith = require('spritesmith');
    
    // Generate our spritesheet
    Spritesmith.run({
      src: [
        __dirname + '/fork.png',
        __dirname + '/github.png',
        __dirname + '/twitter.png'
      ],
      engine: require('canvassmith')
    }, function handleResult (err, result) {
      if (err) {
        throw err;
      }
    
      // Output the image
      fs.writeFileSync(__dirname + '/canvassmith.png', result.image);
      result.coordinates, result.properties; // Coordinates and properties
    });
  7. Add padding between images

    master

    To prevent images from touching in the generated spritesheet, use the padding option in Spritesmith.run(). This value specifies the number of pixels of space to add between each image.

    var fs = require('fs');
    var Spritesmith = require('spritesmith');
    
    // Generate our spritesheet
    Spritesmith.run({
      src: [
        __dirname + '/fork.png',
        __dirname + '/github.png',
        __dirname + '/twitter.png'
      ],
      padding: 20
    }, function handleResult (err, result) {
      if (err) {
        throw err;
      }
    
      // Output the image
      fs.writeFileSync(__dirname + '/padding.png', result.image);
      result.coordinates, result.properties; // Coordinates and properties
    });
  8. Export a spritesheet with spritesheet.processImages()

    master

    After interpreting images, use spritesheet.processImages(images, options) to place them on a canvas and export the final spritesheet.

    Parameters:

    • images: The array of image objects generated by createImages().
    • options: An object containing:
      • padding: (Number) Pixels to use between images (e.g., 2 adds a 2px gap to the right and bottom).
      • exportOpts: (Mixed) Options passed through to the engine for export (e.g., { exportOpts: { quality: 75 } } for gmsmith).
      • algorithm: (String) The packing algorithm to use (default is binary-tree).
      • algorithmOpts: (Object) Options passed to the algorithm (e.g., { algorithmOpts: { sort: false } } for top-down).

    Returns: An object containing:

    • image: A ReadableStream outputting the generated image contents.
    • coordinates: A map from filepath to { x, y, width, height }.
    • properties: The spritesheet's { width, height }.
  9. Initialize a new Spritesmith instance

    master

    You can manually manage the spritesmith lifecycle by using the Spritesmith constructor.

    Parameters (params):

    • engine: (Optional) A String or Object to override the default engine (pixelsmith).
    • engineOpts: (Optional) An Object containing options to pass through to the chosen engine (e.g., { engineOpts: { timeout: 10000 } } for phantomjssmith).
    const Spritesmith = require('spritesmith');
    const spritesmith = new Spritesmith({
      engine: 'canvassmith',
      engineOpts: { /* engine specific options */ }
    });
  10. Interpret images with spritesmith.createImages()

    master

    The spritesmith.createImages(src, callback) method interprets source images via the configured engine without yet placing them on a canvas.

    Parameters:

    • src: An array of filepaths (String[]) or Vinyl objects (Object[]).
    • callback: An error-first function function (err, images).
      • err: Error|null.
      • images: An array of processed image objects. Each object contains metadata about the input image: height and width.