Vivus - Documentation

What is Vivus?

Vivus is a lightweight JavaScript library that animates SVGs. It allows you to bring your static SVG illustrations to life by animating their strokes or fills, creating engaging and visually appealing effects. Whether you’re drawing a simple icon or a complex illustration, Vivus provides a simple and intuitive way to add animation to your SVGs without requiring extensive animation knowledge. It supports various animation types and allows for significant customization.

Key Features and Benefits

Setting up Vivus: Installation and Dependencies

Vivus is available via npm and CDN.

Using npm:

  1. Install Vivus using npm:

    npm install vivus
  2. Import it into your JavaScript code:

    import Vivus from 'vivus';

Using a CDN:

Include the Vivus JavaScript file in your HTML <head>:

<script src="https://cdn.jsdelivr.net/npm/vivus@latest/dist/vivus.min.js"></script>

Vivus has no external dependencies beyond a standard JavaScript environment supporting the Promise object. Older browsers might require a polyfill if Promise is not natively supported.

Basic Usage Example

This example animates an SVG using the oneByOne animation type:

<!DOCTYPE html>
<html>
<head>
<title>Vivus Example</title>
<script src="https://cdn.jsdelivr.net/npm/vivus@latest/dist/vivus.min.js"></script>
</head>
<body>

<svg id="my-svg" width="200" height="200">
  <path d="M100,100 L150,150 L100,150 Z" fill="none" stroke="black" stroke-width="2"/>
</svg>

<script>
  new Vivus('my-svg', {type: 'oneByOne'});
</script>

</body>
</html>

This code will find the SVG with the ID my-svg and animate its path using the oneByOne animation type. Replace the SVG content with your own, and experiment with different animation types and options outlined in the Vivus documentation for more advanced usage.

Core Concepts

Understanding SVG Animation

Vivus animates SVGs by manipulating the stroke-dasharray and stroke-dashoffset properties of SVG paths. Initially, the stroke-dasharray property is set to a value that represents the total length of the path, effectively hiding the stroke. The stroke-dashoffset property is then animated, gradually reducing its value from the total path length to zero. This reveals the stroke, creating the animation effect. Vivus handles this complex process automatically, allowing you to focus on the creative aspects of your animations. For fill animations, a similar approach is used, manipulating the fill properties to create the animation effect.

Types of Animation: One-by-one, Sync, and Random

Vivus offers several animation types to control how the SVG is animated:

The Vivus Object and its Properties

The core of Vivus is the Vivus object. Creating a new Vivus instance initiates the animation. The constructor accepts several options to customize the animation:

Event Handling

Vivus provides events that you can listen for to track the progress of the animation:

To handle these events, you use the on method:

const vivus = new Vivus('my-svg', {
  type: 'oneByOne',
  onReady: function(v){ console.log("Ready") },
  onEnter: function(v){ console.log("Entered") },
  onFrame: function(v){ console.log("Frame") },
  onFinish: function(v){ console.log("Finished") }
});

This code example shows how to use the onReady,onEnter,onFrame, and onFinish events. Replace "my-svg" with the ID of your SVG element. Consult the Vivus documentation for a complete list of events.

Animation Types and Options

One-by-one Animation

The oneByOne animation type draws each path element of the SVG sequentially. This creates a classic “drawing” effect, where elements are revealed one after another. The order of animation follows the order of elements within the SVG file. This is often the most visually appealing option for illustrations that tell a story or reveal elements progressively. The timing of each element can be customized further using pathTimingFunction.

Sync Animation

The simultaneously animation type draws all path elements concurrently. All parts of the SVG animate at the same time, completing their animation at the same rate. This creates a more unified and less sequential animation, suitable for simpler SVGs or when a unified effect is desired. The pathTimingFunction still applies to individual path elements, affecting how their individual animation progresses within the overall simultaneous animation.

Random Animation

The random animation type draws each path element in a random order. This creates a more chaotic and unpredictable animation effect, suitable for designs where a sense of surprise or dynamism is desired. The timing of each element is still controlled by the duration parameter, but the order in which they animate is completely randomized.

Customizing Animation Parameters (duration, delay, etc.)

Several parameters allow you to fine-tune the animation’s behavior:

These parameters are passed as options to the Vivus constructor.

Start and Stop Animation Methods

The Vivus object provides methods to control the animation’s playback:

Controlling Animation Playback: Play, Pause, Reverse

While Vivus doesn’t directly offer explicit play(), pause(), and reverse() methods, you can achieve similar functionality by combining start(), stop(), and potentially manipulating the stroke-dashoffset property directly (although this is generally discouraged as it bypasses Vivus’s internal animation management). For pausing, you can use stop() to freeze the animation. There isn’t a built-in reverse function; achieving reverse animation would require creating a separate Vivus instance with reversed animation parameters or manually manipulating the SVG properties, which is more complex. It is recommended to control the animation through start() and stop() and the options passed to the Vivus constructor to achieve the desired effects.

Advanced Techniques

Animating Multiple SVGs

Animating multiple SVGs involves creating a separate Vivus instance for each SVG element. Each instance will have its own set of options and will control the animation of its corresponding SVG. This allows for independent control over the timing and type of animation for each SVG on the page. You can synchronize animations across multiple SVGs by using the delay parameter to carefully orchestrate their start times.

const vivus1 = new Vivus('svg1', {type: 'oneByOne', duration: 100});
const vivus2 = new Vivus('svg2', {type: 'simultaneously', duration: 150, delay: 1000}); //Starts after 1 second

This example animates two SVGs, identified by the IDs svg1 and svg2, with different animation types and durations. svg2 starts animating 1 second after svg1.

Using Vivus with Different SVG Libraries

Vivus works with SVGs generated from various sources, including vector editing software (Adobe Illustrator, Inkscape) and libraries like Snap.svg or D3.js. As long as the resulting SVG is valid and contains path elements, Vivus will animate it. However, be aware that the complexity and structure of the SVG might affect animation performance. Very large or complex SVGs may require optimization techniques.

Creating Custom Animation Paths

While Vivus primarily animates existing paths within an SVG, you can create custom animation paths programmatically. This usually involves manipulating the SVG’s DOM structure after the SVG is loaded. You would dynamically add new <path> elements or modify existing ones using JavaScript before initializing the Vivus instance. This grants advanced control over the animation flow. However, this method requires a deeper understanding of SVG structure and manipulation in JavaScript.

Performance Optimization

For optimal performance, particularly with large or complex SVGs:

Troubleshooting Common Issues

Remember to consult the Vivus project’s documentation and issue tracker for further assistance and reporting bugs.

Examples and Use Cases

Interactive Illustrations

Vivus excels at creating engaging interactive illustrations. By triggering animations on user interaction (e.g., hover, click), you can add dynamic elements to your designs. This can be achieved by associating events with the animation start, such as a button click initiating the animation of an illustration. This makes static images come alive and enhances the user experience. The start() method becomes particularly useful in such interactive scenarios.

Data Visualization

While not a primary focus, Vivus can be incorporated into data visualization projects. For example, you can use it to animate the appearance of chart elements, highlighting data points as they’re revealed, creating a more visually appealing representation of data. The animation type (e.g., oneByOne) can be used to emphasize the sequential nature of data entry or highlight individual data points. However, for complex data visualizations, dedicated charting libraries are often more suitable.

Loading Animations

Vivus can easily create visually appealing loading animations. You can animate a simple SVG icon or graphic while data is being fetched. This provides a visual cue to the user that something is happening, improving the user experience. The animation can be triggered after the loading process is complete or stopped as needed.

Creating Animated Icons

Vivus is particularly well-suited for creating animated icons. By animating simple SVG path elements, you can easily transform static icons into engaging animated versions. This adds a unique and interactive touch to the user interface. The lightweight nature of Vivus makes it ideal for this use case.

Complex SVG Animation

Vivus can handle complex SVGs, but performance might be affected by the number of paths and the complexity of the SVG structure. For extremely intricate animations, consider optimization techniques such as:

In complex cases, profiling the animation performance with your browser’s developer tools is crucial for identifying and addressing performance bottlenecks. For very complex SVG animations, other animation libraries or custom JavaScript animation routines might be more efficient.

API Reference

Vivus Constructor Options

The Vivus constructor accepts several options to configure the animation:

Methods (play, stop, reset, etc.)

The Vivus object exposes several methods to control animation:

Events

Vivus triggers several events throughout its lifecycle:

Events are handled using the on method:

vivus.on('start', function() { /* ... */ });
vivus.on('frame', function(progress) { /* ... */ });
vivus.on('end', function() { /* ... */ });

Properties

The Vivus object has several properties, accessible using the dot notation:

Direct manipulation of these properties is generally not recommended, and the provided methods are preferred for controlling animation behavior. Modifying these properties directly might lead to unexpected behavior and may break internal synchronization of the animation process.

Note: The specific properties and methods available might vary slightly between versions. Always refer to the latest official documentation for the most accurate and up-to-date information.

Contributing to Vivus

We welcome contributions to Vivus! Whether it’s bug fixes, new features, or improvements to the documentation, your help is valuable. Here’s how you can contribute:

Setting up the Development Environment

  1. Clone the repository: Fork the Vivus repository on GitHub and clone your fork to your local machine:

    git clone git@github.com:YOUR_USERNAME/Vivus.git
    cd Vivus

    Replace YOUR_USERNAME with your GitHub username.

  2. Install dependencies: Install the project dependencies using npm:

    npm install
  3. Run the development server: Start a development server to build and serve the project. The exact command might vary depending on the project’s setup; check the project’s README file for instructions. It will typically involve a command like:

    npm run dev

This will usually start a local development server, enabling you to test your changes.

Coding Style Guide

Adhere to the existing coding style in the project. Generally, this involves:

Refer to the project’s existing codebase for style conventions and examples.

Testing

Vivus likely uses a testing framework (e.g., Jest, Mocha). Before submitting a pull request, ensure your changes are thoroughly tested. The project’s README file will usually contain instructions on running the tests: Typically, this involves a command like:

npm test

Ensure all existing tests pass and add new tests for any new features or bug fixes you’ve implemented. Comprehensive testing helps guarantee code quality and prevent regressions.

Submitting Pull Requests

  1. Create a new branch: Create a new branch for your changes:

    git checkout -b feature/your-feature-name
  2. Commit your changes: Commit your changes with clear and concise commit messages.

  3. Push your branch: Push your branch to your GitHub fork:

    git push origin feature/your-feature-name
  4. Create a pull request: On GitHub, create a pull request from your branch to the main branch of the Vivus repository (usually main or master). Provide a detailed description of your changes and address any comments from reviewers.

  5. Address feedback: Respond to any comments or suggestions from the maintainers, making necessary revisions and pushing updated commits to your branch. Continue this iterative process until the pull request is approved and merged.

Remember to follow the project’s contribution guidelines, which might include specific requirements for code style, testing, and commit messages. Always be respectful and collaborative in your interactions with the project maintainers and other contributors.