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.
oneByOne
, simultaneously
, random
, and delayed
, to customize the animation style.Vivus is available via npm and CDN.
Using npm:
Install Vivus using npm:
npm install vivus
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.
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.
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.
Vivus offers several animation types to control how the SVG is animated:
oneByOne
: Animates each path element sequentially. This creates a drawing effect, where each part of the SVG is drawn one after the other. The order of animation follows the order of the elements in the SVG file.
simultaneously
: Animates all path elements concurrently. This creates a more uniform animation effect, with all parts of the SVG animating at the same time.
random
: Animates each path element in a random order. This provides a more dynamic and less predictable animation effect.
delayed
: Animates elements sequentially, but each element has a delay before starting its animation. This creates a wave-like animation effect.
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:
target
(String or HTMLElement): The ID of the SVG element to animate, or the element itself. This is a required parameter.
type
(String, default: ‘oneByOne’): The animation type (oneByOne
, simultaneously
, random
, delayed
).
duration
(Number, default: 120): The duration of the animation in frames (1 frame = 1/60th of a second).
start
(String, default: ‘auto’): When the animation should start (auto
, manual
, a specific time in milliseconds). Setting it to manual
requires manually starting the animation using the start()
method.
delay
(Number, default: 0): Delay before the animation starts (in milliseconds).
forceRender
(Boolean, default: false): Force a redraw of the SVG. Useful for troubleshooting rendering issues.
onReady
(Function): A callback function to be executed once the animation is ready to be started.
pathTimingFunction
(String, default: ‘linear’): Specifies the timing function for individual path animations.
morphing
(Boolean, default: false): Use morphing animation instead of stroke dash array.
These are just some of the key properties. Refer to the full documentation for a comprehensive list of options.
Vivus provides events that you can listen for to track the progress of the animation:
ready
: Fired when the Vivus instance is ready.
start
: Fired when the animation starts.
frame
: Fired for every frame of the animation, providing the current progress.
end
: Fired when the animation completes.
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.
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
.
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.
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.
Several parameters allow you to fine-tune the animation’s behavior:
duration
: Controls the overall animation duration in frames (1 frame = 1/60th of a second). A higher value extends the animation’s length, making it slower.
delay
: Specifies a delay (in milliseconds) before the animation begins. This can be useful for coordinating animations with other elements on the page.
pathTimingFunction
: This property lets you specify the timing function for each path’s animation using standard CSS timing functions (e.g., linear
, ease
, ease-in-out
, ease-in
, ease-out
, step-start
, step-end
). This controls the pacing of the individual element animations. For example, ease-in-out
will make the animation start and end slowly, while linear
will make it progress at a constant speed.
start
: Controls when the animation begins:
'auto'
: The animation starts immediately.'manual'
: The animation requires a manual start using the vivus.start()
method.These parameters are passed as options to the Vivus
constructor.
The Vivus
object provides methods to control the animation’s playback:
vivus.start()
: Manually starts the animation if start: 'manual'
was specified in the constructor options.
vivus.stop()
: Stops the animation at its current state.
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.
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
.
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.
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.
For optimal performance, particularly with large or complex SVGs:
simultaneously
animation may be faster than oneByOne
for large SVGs.Animation not working: Ensure your SVG is correctly loaded and accessible to Vivus. Double-check the target ID and the path to your SVG file. Confirm that the necessary JavaScript file is correctly included. Browser’s developer tools can help identify JavaScript errors.
Incorrect animation type: Verify you are using the correct animation type (oneByOne
, simultaneously
, random
, delayed
).
Unexpected animation behavior: Check the settings for duration
, delay
, and pathTimingFunction
to ensure they match the desired animation.
Performance issues: If you have performance problems, try simplifying your SVG, reducing the number of path elements, or optimizing the SVG structure. If still slow, profile your code to identify bottlenecks.
Rendering issues: Use the forceRender
option to force a redraw of the SVG to overcome some rendering problems in certain browsers or situations. If problems persist, check for browser compatibility issues. The browser’s developer tools are invaluable for tracking down such issues.
Remember to consult the Vivus project’s documentation and issue tracker for further assistance and reporting bugs.
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.
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.
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.
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.
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:
Breaking down complex paths: Splitting intricate paths into smaller, simpler paths can improve performance.
Using SVG optimization tools: Several tools can help optimize the SVG structure for better performance.
Using a combination of animation techniques: You can combine Vivus with other animation libraries or techniques (e.g., CSS animations) for more sophisticated animation effects.
Lazy loading: If loading multiple complex SVGs at once is an issue, consider lazy loading them so that only the currently visible elements are animated.
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.
The Vivus
constructor accepts several options to configure the animation:
target
(String | HTMLElement): (Required) The ID of the SVG element or the element itself to animate.
type
(String): The animation type. Options include: 'oneByOne'
, 'simultaneously'
, 'random'
, 'delayed'
. Defaults to 'oneByOne'
.
duration
(Number): The animation duration in frames (1 frame = 1/60th of a second). Defaults to 120.
start
(String | Number): When the animation starts. Options include: 'auto'
(immediately), 'manual'
(requires manual start with start()
method), or a number representing a delay in milliseconds. Defaults to 'auto'
.
delay
(Number): The delay before the animation begins (in milliseconds). Defaults to 0.
forceRender
(Boolean): Forces a redraw of the SVG. Useful for troubleshooting rendering issues. Defaults to false
.
onReady
(Function): Callback function executed when the animation is ready to start.
onEnter
(Function): Callback function executed at the start of the animation.
onFrame
(Function): Callback function executed every animation frame. The progress value is passed as an argument.
onFinish
(Function): Callback function executed when the animation completes.
pathTimingFunction
(String): Timing function for each path’s animation (e.g., 'linear'
, 'ease'
, 'ease-in-out'
). Defaults to 'linear'
.
morphing
(Boolean): Use morphing animation instead of stroke dash array. Defaults to false
.
The Vivus
object exposes several methods to control animation:
start()
: Manually starts the animation if start: 'manual'
was used in the constructor.
stop()
: Stops the animation at its current state.
reset()
: Resets the animation to its initial state.
destroy()
: Removes the Vivus instance and cleans up events.
getProgress()
: Returns the current progress of the animation (0-1).
setProgress(progress)
: Sets the animation progress directly to a specific value (0-1).
Vivus triggers several events throughout its lifecycle:
ready
: Fired when the Vivus instance is ready.
start
: Fired when the animation begins.
frame
: Fired for each animation frame. Passes the current progress as an argument to the callback function.
end
: Fired when the animation completes.
Events are handled using the on
method:
.on('start', function() { /* ... */ });
vivus.on('frame', function(progress) { /* ... */ });
vivus.on('end', function() { /* ... */ }); vivus
The Vivus
object has several properties, accessible using the dot notation:
opts
: The options object passed to the constructor.
frameLength
: The duration of the animation in frames (same as the duration
option).
duration
: The duration of the animation in milliseconds.
currentFrame
: The current frame of the animation.
totalFrame
: The total number of frames in the animation.
isDrawing
: Boolean indicating whether the animation is currently running.
isComplete
: Boolean indicating whether the animation has completed.
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.
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:
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.
Install dependencies: Install the project dependencies using npm:
npm install
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.
Adhere to the existing coding style in the project. Generally, this involves:
Refer to the project’s existing codebase for style conventions and examples.
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.
Create a new branch: Create a new branch for your changes:
git checkout -b feature/your-feature-name
Commit your changes: Commit your changes with clear and concise commit messages.
Push your branch: Push your branch to your GitHub fork:
git push origin feature/your-feature-name
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.
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.