Animate Programmatically
SVGator offers now a powerful JS API to enable external, code-based and event-driven control of your animated SVG projects.
This document describes how to export a project as "programmatic", how to access the Player API object and how to synchronize events. For available API properties, methods and the events interface please refer to the full API documentation.
I. Export as "Programmatic"
If you choose "programmatic" as the starting option for your project during export, no user action will trigger the animation. Instead, it can be started only through API actions. To be noted that the API is available for all projects exported as Javascript, regardless of their starting option (assuming you have a Pro account).
II. Access the Player Object
SVGator's JS API can be accessed separately for each SVG on the page, as svgatorPlayer
property of the DOM element. Assuming the main auto-generated id of your SVG is eUVORkEd0zb1
, the following JS code will return the main API object:
const element = document.getElementById('eUVORkEd0zb1');
const player = element ? element.svgatorPlayer : {};
// usage:
if (player.play) {
player.play();
}
III. Synchronize Events
To be noted that the code above will work only after SVGator's player is fully loaded an initialized on your SVG file. If you want to perform a given API action immediately after your animation is loaded, you can use the ready
method of the player
object.
For instance, the code below will start the animation once the player is fully loaded:
const element = document.getElementById('eUVORkEd0zb1');
element.svgatorPlayer.ready(function() {
// this refers to the player object
this.play();
});
where this
refers to Player Object. Since arrow function expressions do not have their own this
, the player
object is also exposed as the 1st parameter of the callback:
const element = document.getElementById('eUVORkEd0zb1');
element.svgatorPlayer.ready(player => player.play());
If player.ready()
is called after the player
is already loaded, its callback executes instantly.
One can auto-detect if the player is already available using totalTime
property, as follows:
const element = document.getElementById('eUVORkEd0zb1');
const player = element ? element.svgatorPlayer : {};
if (player.totalTime) {
player.play();
} else {
player.ready(p => p.play());
}
The Player API also emits a ready
DOM event on the SVG DOM Node itself, on which one can listen as follows:
const element = document.getElementById('eUVORkEd0zb1');
const callback = function(event) {
if (!event.target.svgatorPlayer) {
return;
}
event.target.svgatorPlayer.play();
};
element.addEventListener('ready', callback);
Find more details and the API in work under the Live Demo section of the API documentation.
More articles:
Still got questions? Send us an email at contact@svgator.com and we will get back to you as soon as we can.