svg-text-animate

repository·master·Indexed 42 days ago

https://github.com/oubenruing/svg-text-animate

A JavaScript library (v1.4.1) that converts text into SVG stroke animations in the browser. It supports custom font files (WOFF, OTF, TTF), icon fonts, and provides two rendering modes: CSS-based animations via CSSCreator or SMIL-based animations via SVGCreator. Developers can control animation timing, stroke styles, and orchestration modes such as sync, onebyone, or delay.

Tokens
2.8K
Snippets
9
Records
15
Agent score
52%

What's inside svg-text-animate

  1. Choose an animation Creator mode

    master

    The creator parameter (passed to the constructor) determines how the animation is implemented:

    • css (default): Uses CSSCreator. Creates a CSS-based SVG animation using <style> tags and @keyframes.
    • svg: Uses SVGCreator. Creates a SMIL-based SVG animation using <animate> tags. Use this if CSS animations are not supported in your environment.

    Limitations of svg mode:

    1. timing-function is always linear.
    2. fill-mode only supports forwards or none.
    3. direction is always normal.
  2. Animate text using create() and setFont()

    master

    To render the animation, you must first load the font and then call the create method.

    Workflow

    1. setFont(): An asynchronous method that loads the font file provided in the constructor. It returns a Promise and should be called once.
    2. create(text, selector): Generates the SVG animation from the provided text string and inserts it into the DOM element matching the selector. This method clears the selector's content before inserting.

    Note: add(text, selector) (available since v1.2.0) performs the same action but inserts the animation without clearing the selector first.

    Example

    await opensans.setFont();
    opensans.create("Hello World", "#target-element");
    import SVGTextAnimate from 'svg-text-animate';
    
    const opensans = new SVGTextAnimate("https://path/to/font.woff", {
      "duration": 500,
      "mode": "sync"
    }, {
      "stroke": "white",
      "font-size": 23
    });
    
    // 1. Load font
    await opensans.setFont();
    
    // 2. Create animation
    opensans.create("Try it", ".button");
  3. Install svg-text-animate

    master

    You can install the library via NPM or include it directly in your HTML using a CDN link.

    NPM:

    npm i svg-text-animate

    CDN:

    <script src="https://cdn.jsdelivr.net/gh/oubenruing/svg-text-animate@latest/dist/svg-text-animate.min.js"></script>
    npm i svg-text-animate
  4. Configure visual appearance with Stroke

    master

    The stroke object controls the visual properties of the generated SVG text.

    NameTypeDefaultDescription
    strokeString#000000Hex color of the stroke
    stroke-widthString1pxWidth of the stroke
    font-sizeNumber72Output font size
    fill-colorStringtransparentFill color of the text
  5. Configure animation timing with Options

    master

    The options object controls the animation lifecycle. These properties map closely to CSS animation properties.

    NameTypeDefaultDescription
    durationNumber1000Length of one cycle in milliseconds
    timing-functionStringlinearSame as CSS animation-timing-function
    iteration-countNumber1Same as CSS animation-iteration-count
    directionStringnormalSame as CSS animation-direction
    fill-modeStringforwardsSame as CSS animation-fill-mode
    modeStringsyncAnimation sequence: sync (all at once), onebyone (sequential), or delay (each symbol starts $n$ ms after the previous)
    delayNumber0Only used when mode is set to delay
  6. Animate Icon Fonts (e.g., FontAwesome)

    master

    To animate icons from icon fonts, use the Unicode hex code of the icon with String.fromCharCode() as the first argument to the create method.

    Example

    // Animating a FontAwesome icon
    fontawesome.setOptions({
      "duration": 2000,
      "mode": "sync"
    }).setStroke({
      "stroke": "white",
      "font-size": 22
    }).create(String.fromCharCode(0xf581), "#symbols");
    // Using hex code from iconfont website
    // Example: 0xf581
    opensans.create(String.fromCharCode(0xf581), "#symbols");
  7. Load font from ArrayBuffer with setFontFromBuffer()

    master

    If you have the font data already loaded as an ArrayBuffer, use setFontFromBuffer() to load it into the instance. This method returns the current instance.

    // Assuming fontBuffer is an ArrayBuffer
    opensans.setFontFromBuffer(fontBuffer);
  8. Initialize SVGTextAnimate with the Constructor

    master

    To create an instance of SVGTextAnimate, use the following signature:

    SVGTextAnimate(fontfile, options, stroke, creator)

    Parameters

    • fontfile (String, Required): Path to a font file (WOFF, OTF, or TTF).
    • options (Object, Required): Configuration for the animation timing and behavior.
    • stroke (Object, Required): Configuration for the visual appearance (stroke, size, etc.).
    • creator (String, Optional): The animation mode. Defaults to css. Use svg for SMIL SVG animations if CSS is not supported.

    Note: In version 1.2.0, font-size was moved from options to the stroke object.

    import SVGTextAnimate from 'svg-text-animate';
    
    const opensans = new SVGTextAnimate("https://path/to/font.woff", {
      "duration": 300,
      "direction": "normal",
      "fill-mode": "forwards",
      "delay": 150,
      "mode": "delay"
    }, {
      "stroke": "#005792",
      "stroke-width": "2px",
      "font-size": 55,
      "fill-color":"white"
    });
  9. Update configuration with setOptions and setStroke

    master

    You can dynamically update the animation or visual settings using chainable methods. Both methods return the current instance to allow chaining.

    • setOptions(options): Updates the animation timing/behavior settings. Accepts an object with the same keys as the initial options parameter.
    • setStroke(stroke): Updates the visual stroke and font settings. Accepts an object with the same keys as the initial stroke parameter.

    Example

    opensans
      .setOptions({
        "duration": 500,
        "mode": "sync"
      })
      .setStroke({
        "stroke": "white",
        "font-size": 23
      })
      .create("Updated Text", ".container");
    opensans.setOptions({
      "duration": 500,
      "timing-function": "linear",
      "direction": "normal",
      "fill-mode": "forwards",
      "delay": 50,
      "mode": "sync"
    }).setStroke({
      "stroke": "white",
      "stroke-width": "2px",
      "font-size": 23,
      "fill-color":"white"
    }).create("Try it", ".button");
  10. Configure stroke options

    master

    You can customize the appearance of the text stroke by providing a stroke options object. The default values are:

    • stroke: The color of the stroke (default: '#000')
    • stroke-width: The thickness of the stroke (default: '1px')
    • font-size: The font size used for calculating stroke properties (default: 72)
    • fill-color: The color used to fill the text (default: 'transparent')

    Note that stroke-width uses kebab-case to match CSS property names.

    const strokeOptions = {
      stroke: '#ff0000',
      'stroke-width': '2px',
      'font-size': 48,
      'fill-color': '#ffffff'
    };
  11. Configure animation options

    master

    When initializing an animation, you can provide an options object to control the timing and behavior of the SVG text animation. If no options are provided, the following defaults are used:

    • duration: Animation duration in milliseconds (default: 1000)
    • timing-function: CSS timing function (default: 'linear')
    • iteration-count: Number of times the animation repeats (default: 1)
    • direction: Animation direction ('normal', 'reverse', 'alternate', or 'alternate-reverse') (default: 'normal')
    • fill-mode: CSS fill mode ('none', 'forwards', 'backwards', or 'both') (default: 'forwards')
    • delay: Delay before the animation starts in milliseconds (default: 0)
    • mode: Animation synchronization mode ('sync' or 'async') (default: 'sync')

    Note that keys like timing-function, iteration-count, and fill-mode use kebab-case to match CSS property names.

    const options = {
      duration: 2000,
      'timing-function': 'ease-in-out',
      'iteration-count': Infinity,
      direction: 'alternate',
      'fill-mode': 'forwards',
      delay: 500,
      mode: 'async'
    };
  12. Configure AnimationOptions

    master

    The AnimationOptions interface defines how the text animation behaves over time. You can control the speed, repetition, and the relationship between individual character animations using the mode property.

    Key properties include:

    • duration: Total animation time in milliseconds.
    • mode: Determines the animation pattern. Use "sync" for simultaneous animation, "delay" for staggered animation, or "onebyone" for sequential animation.
    • delay: The delay between individual character animations in milliseconds.
    • "timing-function": CSS timing function (e.g., ease-in) or SVG calcMode.
    • "iteration-count": Number of times to repeat, or strings like "infinite" or "indefinite".
    • direction: Animation direction.
    • "fill-mode": CSS fill mode behavior.
    const options: AnimationOptions = {
      duration: 1000,
      mode: 'onebyone',
      delay: 50,
      'timing-function': 'ease-out',
      'iteration-count': 'infinite'
    };