KeyframeKit
Unlock full playback control over your CSS animations with JavaScript.
What is this?
A lightweight TypeScript library that converts CSS @keyframes animations into Web Animations API-compatible animations, letting you play CSS-defined animations from JavaScript with full playback control and hardware-accelerated performance.
Read more | Live Demo
Installation
npm install keyframekit/* Import the module directly: */
import KeyframeKit from 'https://cdn.jsdelivr.net/npm/keyframekit/dist/index.min.js'Usage
Playing CSS-defined animations with JS
In your CSS:
@keyframes rotate-small { ... }Then, in JS:
import KeyframeKit from 'keyframekit';
const documentStyleSheets = await KeyframeKit.getDocumentStyleSheetsOnLoad();
// get animation keyframes from the document's stylesheets
const rotateSmallAnimKeyframes = KeyframeKit.getStyleSheetKeyframes({
of: 'rotate-small',
in: documentStyleSheets
});
// then, define your animation
const rotateSmallAnim = rotateSmallAnimKeyframes.toKeyframeEffect({
duration: 700,
easing: 'ease'
});
// finally, attach it to an element:
const attachedAnim = rotateSmallAnim.toAnimation({
target: document.querySelector('.el')
});
attachedAnim.play();The primary reason to play your animation with JS is because you get way more control over its playback:
attachedAnim.pause();
attachedAnim.playbackRate = -1;
const progress = attachedAnim.overallProgress; // 0 to 1 (Baseline newly available)
await attachedAnim.finished;Importing animations directly from a CSS file
Instead of getting an animation from the document's stylesheets, you can also import it directly from a CSS file.
import KeyframeKit from 'keyframekit';
const styleSheet = await KeyframeKit.importStyleSheet('./styles.css');
// get animation keyframes from stylesheet
const rotateSmallAnimKeyframes = KeyframeKit.getStyleSheetKeyframes({
of: 'rotate-small',
in: styleSheet
});Note:
@importrules won't be resolved in imported stylesheets. See more.
Defining animations in JS
The KeyframeEffectParameters class provides a more convenient way to define your animations in JS than is offered natively.
It's useful for when you want to have all your animation code in one place.
import { KeyframeEffectParameters } from 'keyframekit';
// define your animation
const linkTextHoverAnim = new KeyframeEffectParameters({
keyframes: {
// 0 to 1. equivalent to CSS keyframe percentage values:
offset: [0, 0.499, 0.5, 1],
// respective CSS property keyframes:
clipPath: ['inset(0 0 0 0)', 'inset(100% 0 0 0)', 'inset(0 0 100% 0)', 'inset(0 0 0 0)'],
top: ['0', '-20px', '20px', '0']
},
options: {
duration: 700,
easing: 'ease'
}
});
// then, attach it to an element:
const attachedAnim = linkTextHoverAnim.toAnimation({
target: document.querySelector('.link')
});
attachedAnim.play();