About
While working with the Web animation APII was surprised that there wasn’t an easy way to import animation keyframes directly from your CSS. You had to redefine them in JS, with a completely different format. That’s why I wrote a typed-to-spec library that you can convert from one to the other, so you can play your CSS-defined animations directly in JS. Along the way I’ve also added some other useful tools for working with the API.
Installation
Usage
Play 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 main reason to play your animation with JS is because you get much more control over its playback:
attachedAnim.pause();
attachedAnim.playbackRate = -1;
const progress = attachedAnim.overallProgress; // 0 to 1 (Baseline newly available)
await attachedAnim.finished;…and more.
Import animations directly from a CSS file
Instead of pulling 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: This doesn’t solve anything
@importrules in the style sheet. See here.
Defining animations in JS
The KeyframeEffectParameters class provides a more convenient way to define your animations in JS than is offered by default.
This is useful if 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();Full reference
See here.
Typing
This library is fully compatible with native JS, but also provides full support for compliant types, including declaration files and source maps.
License
OF
#KeyframeKit


