Certainly! Below is an implementation of an Animator class in JavaScript that provides a flexible API for animating DOM elements' CSS properties. The class is designed as a static class with an animate method and supports various animation types, including complex ones like spring and elastic. Here's a breakdown of the implementation:
Key Features:
-
Static Class Structure: The Animator class is designed with static methods and properties, allowing you to call Animator.animate directly without instantiating the class.
-
Animation Types: Supports a range of animation types:
- Linear: Constant speed from start to finish.
- Ease, EaseIn, EaseOut, EaseInOut: Various easing functions for smooth transitions.
- Spring: Simulates a spring-like motion with oscillations.
- Elastic: Provides an elastic effect with overshooting and bouncing.
- SpringElastic: Combines both spring and elastic effects.
-
Easing Functions: Implements standard easing functions and more complex ones for spring and elastic animations.
-
Animation Loop: Uses requestAnimationFrame for smooth, performant animations.
-
Flexible Configuration: Accepts a configuration object to specify the target element, property, target value, duration, unit, and animation type.
-
Promise-Based: Returns a promise that resolves when the animation is complete, allowing for asynchronous handling.
Usage Example:
const myElement = document.getElementById('myElement');
Animator.animate({
element: myElement,
property: 'width',
propertyUnit: 'px',
value: 300,
duration: 1000,
type: Animator.types.springElastic
}).then(() => {
console.log('Animation completed!');
});
Full Implementation:
class Animator {
static types = {
linear: 'linear',
ease: 'ease',
easeIn: 'easeIn',
easeOut: 'easeOut',
easeInOut: 'easeInOut',
spring: 'spring',
elastic: 'elastic',
springElastic: 'springElastic',
};
static easingFunctions = {
linear: (t) => t,
ease: (t) =>
t < 0.5
? 4 * t * t * t
: 1 - Math.pow(-2 * t + 2, 3) / 2,
easeIn: (t) => t * t * t,
easeOut: (t) => 1 - Math.pow(1 - t, 3),
easeInOut: (t) =>
t < 0.5
? 4 * t * t * t
: 1 - Math.pow(-2 * t + 2, 3) / 2,
// Spring and Elastic will have their own functions
};
static animate({ element, property, propertyUnit = '', value, duration = 1000, type = Animator.types.linear }) {
return new Promise((resolve, reject) => {
if (!element || !property || typeof value !== 'number') {
reject(new Error('Invalid parameters for animation.'));
return;
}
const startValue = parseFloat(getComputedStyle(element)[property]);
const unit = propertyUnit;
const changeInValue = value - startValue;
const startTime = performance.now();
const animateFrame = (currentTime) => {
const elapsed = currentTime - startTime;
let progress = Math.min(elapsed / duration, 1);
let easedProgress;
switch (type) {
case Animator.types.linear:
case Animator.types.ease:
case Animator.types.easeIn:
case Animator.types.easeOut:
case Animator.types.easeInOut:
easedProgress = Animator.easingFunctions[type](progress);
break;
case Animator.types.spring:
easedProgress = Animator.spring(progress);
break;
case Animator.types.elastic:
easedProgress = Animator.elastic(progress);
break;
case Animator.types.springElastic:
easedProgress = Animator.springElastic(progress);
break;
default:
easedProgress = progress;
}
const currentValue = startValue + changeInValue * easedProgress;
element.style[property] = currentValue + unit;
if (elapsed < duration) {
requestAnimationFrame(animateFrame);
} else {
element.style[property] = value + unit;
resolve();
}
};
requestAnimationFrame(animateFrame);
});
}
// Spring easing function
static spring(t) {
const c4 = (2 * Math.PI) / 3;
return t === 0
? 0
: t === 1
? 1
: 1 + Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * c4);
}
// Elastic easing function
static elastic(t) {
const c4 = (2 * Math.PI) / 3;
return t === 0
? 0
: t === 1
? 1
: -Math.pow(2, 10 * t - 10) * Math.sin((t * 10 - 10.75) * c4);
}
// Combined Spring and Elastic easing function
static springElastic(t) {
// Simple combination: average of spring and elastic
const spring = Animator.spring(t);
const elastic = Animator.elastic(t);
return (spring + elastic) / 2;
}
}
// Example usage:
// Assuming there is an element with id 'myElement' in the DOM
document.addEventListener('DOMContentLoaded', () => {
const myElement = document.getElementById('myElement');
if (myElement) {
Animator.animate({
element: myElement,
property: 'width',
propertyUnit: 'px',
value: 300,
duration: 1000,
type: Animator.types.springElastic,
}).then(() => {
console.log('Animation completed!');
});
}
});
Explanation:
-
Animator.types: An object containing all supported animation types for easy reference.
-
Animator.easingFunctions: A collection of standard easing functions. These are mathematical functions that define the rate of change of a parameter over time.
-
Animator.animate:
- Parameters: Accepts an object with
element, property, propertyUnit, value, duration, and type.
- Validation: Checks if the necessary parameters are provided and valid.
- Initial Setup: Retrieves the starting value of the property and calculates the change required.
- Animation Loop: Uses
requestAnimationFrame to update the property on each frame based on the elapsed time and the selected easing function.
- Completion: Ensures the final value is set and resolves the promise.
-
Spring and Elastic Functions: Custom easing functions that create more natural and physics-based animations.
- spring(t): Simulates a spring motion using a damped sine wave.
- elastic(t): Creates an elastic effect with overshooting.
- springElastic(t): Combines both spring and elastic effects by averaging their outputs.
-
Example Usage: Demonstrates how to use the Animator.animate method to animate the width of an element with id myElement using the springElastic type.
Notes:
- The
animate method returns a promise, allowing you to perform actions after the animation completes.
- The easing functions can be further customized or expanded based on specific needs.
- Error handling is included to ensure that invalid parameters are caught early.
This implementation provides a robust and flexible way to animate DOM elements with various easing effects, closely simulating the behavior found in libraries like React and Expo.