KeyframeKit
Intuitive, powerful and performant tools for working with CSS animations in JavaScript.
Intuitive, powerful and performant tools for working with CSS animations in JavaScript.
While working with the Web Animations API, I was surprised there wasn't an easy way to import animation keyframes directly from your CSS. You had to re-define them in JS, using a completely different format. So, I wrote a typed, spec-compliant library to convert. Along the way, I also added some other useful utilities for working with the API.
npm install keyframekitIn your CSS:
@keyframes rotate-small { ... }Then, in JS:
import KeyframeKit from 'keyframekit';
const documentStyleSheets = await KeyframeKit.getDocumentStyleSheetsOnLoad();
// get animation keyframes from stylesheet
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;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 stylesheets imported in this way. More info.
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();This library is fully compatable with native JS, but it also has full spec-compliant type support, including declaration files and source maps.