flip-animation
v1.0.2
Published
A lightweight FLIP animation library for smooth transitions
Downloads
311
Maintainers
Readme
FLIP Animation Library
A lightweight JavaScript library for creating smooth FLIP animations with ease.
What is FLIP Animation?
FLIP is an acronym for First, Last, Invert, Play:
- First: Record the initial state of the element
- Last: Record the final state of the element
- Invert: Calculate the difference and apply an inverse transform
- Play: Animate from the inverted state to the final state
This technique allows for smooth animations even when elements change position, size, or other properties.
Installation
npm
npm install flip-animationDirect Download
Download the FLIPAnimation.js file from the repository and include it in your project:
<script src="FLIPAnimation.js"></script>Using ES Modules
For modern JavaScript projects, you can import the library as an ES module:
import { FLIPAnimation, easingFunctions } from 'flip-animation';API Reference
FLIPAnimation Class
Constructor
const flipAnimation = new FLIPAnimation(element, options);Parameters
element (required)
- Type:
HTMLElement - Description: The DOM element to animate
- Example:
const element = document.getElementById('myElement'); // or const element = document.querySelector('.my-class');
options (optional)
- Type:
FLIPAnimationOptions - Description: Configuration options for the animation
- Default:
{ duration: 300, easing: 'ease-out', properties: ['transform', 'opacity'], fill: 'forwards' }
FLIPAnimationOptions Interface
interface FLIPAnimationOptions {
duration?: number;
easing?: string | EasingFunction;
properties?: string[];
fill?: 'none' | 'forwards' | 'backwards' | 'both' | 'auto';
}duration (optional)
- Type:
number - Description: Animation duration in milliseconds
- Default:
300 - Example:
{ duration: 500 } // 500ms animation { duration: 1000 } // 1 second animation { duration: 200 } // 200ms fast animation
easing (optional)
- Type:
string | EasingFunction - Description: Easing function or CSS easing string
- Default:
'ease-out' - Options:
- CSS Easing String: Any valid CSS easing string
'linear''ease''ease-in''ease-out''ease-in-out''cubic-bezier(0.25, 0.1, 0.25, 1)''steps(4, end)'
- Built-in Easing Function Name: String name of a built-in easing function
'linear''easeInQuad','easeOutQuad','easeInOutQuad''easeInCubic','easeOutCubic','easeInOutCubic''easeInQuart','easeOutQuart','easeInOutQuart''easeInQuint','easeOutQuint','easeInOutQuint''easeInSine','easeOutSine','easeInOutSine''easeInExpo','easeOutExpo','easeInOutExpo''easeInCirc','easeOutCirc','easeInOutCirc''easeInElastic','easeOutElastic','easeInOutElastic''easeInBack','easeOutBack','easeInOutBack''easeInBounce','easeOutBounce','easeInOutBounce'
- Custom Easing Function: A function that takes a progress value (0-1) and returns a new progress value
type EasingFunction = (t: number) => number;
- CSS Easing String: Any valid CSS easing string
- Example:
{ easing: 'ease-out' } { easing: 'cubic-bezier(0.25, 0.1, 0.25, 1)' } { easing: 'easeInOutCubic' } { easing: (t) => t * t } // Custom quadratic easing
properties (optional)
- Type:
string[] - Description: Array of CSS properties to animate
- Default:
['transform', 'opacity'] - Options: Any valid CSS property name
'transform': Animate position and size changes using transform'opacity': Animate opacity changes'height': Animate height changes'width': Animate width changes'color': Animate color changes'background-color': Animate background color changes'margin': Animate margin changes'padding': Animate padding changes'border-radius': Animate border radius changes- Any other animatable CSS property
- Example:
{ properties: ['transform', 'opacity'] } // Default { properties: ['height'] } // Only animate height { properties: ['transform', 'opacity', 'height'] } // Multiple properties { properties: ['width', 'height'] } // Animate both width and height
fill (optional)
- Type:
'none' | 'forwards' | 'backwards' | 'both' | 'auto' - Description: Animation fill mode, determines how the animation applies styles before and after execution
- Default:
'forwards' - Options:
'none': The animation will not apply any styles to the target when it's not executing'forwards': The target will retain the computed values set by the last keyframe encountered during execution'backwards': The animation will apply the values defined in the first relevant keyframe as soon as it is applied to the target, and retain this during the animation-delay period'both': The animation will follow the rules for both forwards and backwards, thus extending the animation properties in both directions'auto': The animation will apply the fill mode as defined by the animation-fill-mode property of the element
- Example:
{ fill: 'forwards' } // Default, retain final state { fill: 'none' } // Don't retain any state { fill: 'both' } // Retain both initial and final state
Methods
start(): void
Records the initial state of the element.
Usage:
flipAnimation.start();Description:
- Records the element's current position, size, and computed styles
- Must be called before making any changes to the element
- Must be called before
end()
end(): Animation
Calculates the animation and returns the Animation object.
Usage:
const animation = flipAnimation.end();Returns: Animation - A Web Animations API Animation object
Description:
- Calculates the difference between the initial and final states
- Applies an inverse transform to create the FLIP effect
- Starts the animation from the inverted state to the final state
- Must be called after
start()and after making changes to the element
Throws: Error if start() was not called first
Easing Functions
The library includes a variety of built-in easing functions that can be used with the easing option:
Quadratic
easeInQuad: Accelerating from zero velocityeaseOutQuad: Decelerating to zero velocityeaseInOutQuad: Accelerating until halfway, then decelerating
Cubic
easeInCubic: Accelerating from zero velocityeaseOutCubic: Decelerating to zero velocityeaseInOutCubic: Accelerating until halfway, then decelerating
Quartic
easeInQuart: Accelerating from zero velocityeaseOutQuart: Decelerating to zero velocityeaseInOutQuart: Accelerating until halfway, then decelerating
Quintic
easeInQuint: Accelerating from zero velocityeaseOutQuint: Decelerating to zero velocityeaseInOutQuint: Accelerating until halfway, then decelerating
Sinusoidal
easeInSine: Accelerating from zero velocityeaseOutSine: Decelerating to zero velocityeaseInOutSine: Accelerating until halfway, then decelerating
Exponential
easeInExpo: Accelerating from zero velocityeaseOutExpo: Decelerating to zero velocityeaseInOutExpo: Accelerating until halfway, then decelerating
Circular
easeInCirc: Accelerating from zero velocityeaseOutCirc: Decelerating to zero velocityeaseInOutCirc: Accelerating until halfway, then decelerating
Elastic
easeInElastic: Elastic effect at the beginningeaseOutElastic: Elastic effect at the endeaseInOutElastic: Elastic effect at both ends
Back
easeInBack: Pull back before moving forwardeaseOutBack: Overshoot and come backeaseInOutBack: Pull back, then overshoot and come back
Bounce
easeInBounce: Bounce effect at the beginningeaseOutBounce: Bounce effect at the endeaseInOutBounce: Bounce effect at both ends
Usage Examples
// Using CSS easing string
const animation1 = new FLIPAnimation(element, {
easing: 'ease-out'
});
// Using built-in easing function name
const animation2 = new FLIPAnimation(element, {
easing: 'easeInOutCubic'
});
// Using custom easing function
const customEasing = (t) => t * t * t; // Cubic easing
const animation3 = new FLIPAnimation(element, {
easing: customEasing
});Usage Examples
Basic Example
const element = document.getElementById('myElement');
// Create FLIP animation instance
const flipAnimation = new FLIPAnimation(element, {
duration: 500,
easing: 'ease-out',
properties: ['transform', 'opacity']
});
// Record initial state
flipAnimation.start();
// Change the element's state
element.classList.toggle('active');
// Execute the animation
const animation = flipAnimation.end();
// Listen for animation events
animation.addEventListener('finish', () => {
console.log('Animation finished!');
});Height Transition Example
const container = document.getElementById('container');
// Create FLIP animation instance for height
const flipAnimation = new FLIPAnimation(container, {
duration: 500,
easing: 'ease-out',
properties: ['height']
});
// Record initial state
flipAnimation.start();
// Change the content (this will change the height)
container.innerHTML = '<p>New content that changes the height</p>';
// Execute the animation
flipAnimation.end();List Sorting Animation
const list = document.getElementById('list');
// Create FLIP animation instance
const flipAnimation = new FLIPAnimation(list, {
duration: 600,
easing: 'ease-out',
properties: ['transform']
});
// Record initial state
flipAnimation.start();
// Shuffle the list items
const items = Array.from(list.children);
items.sort(() => Math.random() - 0.5);
items.forEach(item => list.appendChild(item));
// Execute the animation
flipAnimation.end();Multiple Properties Animation
const element = document.getElementById('myElement');
// Create FLIP animation instance for multiple properties
const flipAnimation = new FLIPAnimation(element, {
duration: 800,
easing: 'easeInOutCubic',
properties: ['transform', 'opacity', 'height']
});
// Record initial state
flipAnimation.start();
// Change multiple properties
element.classList.add('expanded');
// Execute the animation
flipAnimation.end();React Integration Example
import React, { useState, useRef, useEffect } from 'react';
import { FLIPAnimation } from 'flip-animation';
function AnimatedComponent() {
const [expanded, setExpanded] = useState(false);
const elementRef = useRef(null);
const animationRef = useRef(null);
useEffect(() => {
if (elementRef.current) {
animationRef.current = new FLIPAnimation(elementRef.current, {
duration: 600,
easing: 'ease-in-out',
properties: ['height']
});
}
}, []);
const toggleExpand = () => {
if (animationRef.current && elementRef.current) {
animationRef.current.start();
setExpanded(!expanded);
// Wait for React to update the DOM
requestAnimationFrame(() => {
requestAnimationFrame(() => {
animationRef.current.end();
});
});
}
};
return (
<div>
<button onClick={toggleExpand}>
{expanded ? '收起' : '展开'}
</button>
<div ref={elementRef}>
<p>基础内容</p>
{expanded && <p>展开后的额外内容</p>}
</div>
</div>
);
}Live Examples
1. Basic Size and Position Change
Demonstrates a simple box that changes size and position with FLIP animation.
2. Height Transition
Shows how to animate height changes when content expands or collapses.
3. List Sorting Animation
Shows how to animate list items when sorting them.
Browser Support
- Chrome
- Firefox
- Safari
- Edge
The library uses the Web Animations API, which is supported in all modern browsers. For older browsers, you may need to include a polyfill.
Performance Tips
- Use
transformandopacityfor best performance, as they don't trigger layout - Avoid animating properties that cause layout shifts (e.g., width, height, margin)
- For complex animations, consider using
requestAnimationFramefor better control - When animating multiple elements, use
Promise.allto wait for all animations to complete
TypeScript Support
This library is written in TypeScript and provides full type definitions.
import { FLIPAnimation, FLIPAnimationOptions, easingFunctions } from 'flip-animation';
const options: FLIPAnimationOptions = {
duration: 500,
easing: 'ease-out',
properties: ['transform', 'opacity']
};
const flipAnimation = new FLIPAnimation(element, options);License
MIT License
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
