认识一下 Animatable,一个使用 WAAPI 作为组件的微型 Web 组件 💫
额外奖励:使用 StencilJS 的高阶组件(HOC)
Web Animations API是使用 JS 而非 CSS 为任何 HTML 元素制作动画的另一种方式。如果您熟悉Animate.css ,那么Animatable就是您正在寻找的动画序列!🌟
<animatable-component
autoplay
easing="ease-in-out"
duration="800"
delay="300"
animation="zoomIn"
iterations="Infinity"
direction="alternate"
>
<h1>Hello World</h1>
</animatable-component>
正如您所见,我们以声明的方式使用Web Animations API(像其他任何元素一样使用 HTML 元素),我们可以说Animate.css之于 CSS 就像Animatable之于 JS 💅
如果您使用的是VanillaJS(无框架集成),则只需要在之前导入脚本:
<!-- Add Web Animations Polyfill :) --> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.2/web-animations.min.js"></script> | |
<script type="module" src="https://unpkg.com/@proyecto26/animatable-component@1.0.0/dist/animatable-component/animatable-component.esm.js"></script> | |
<script nomodule="" src="https://unpkg.com/@proyecto26/animatable-component@1.0.0/dist/animatable-component/animatable-component.js"></script> | |
<animatable-component autoplay iterations="3" animation="heartBeat" easing="ease-in" duration="1000"> | |
<h1>Proof that Tony Stark has a heart ✵</h1> | |
</animatable-component> |
我们可以看到,它就像Animate.css,但具有超能力,因为我们可以在创建另一个动画之前保留前一个动画的最后状态(不透明度、变换等),而无需向元素添加和删除类。
这里有默认动画,而不是直接使用关键帧👋
如果您想添加其他精彩的动画,您可以从存储库提交拉取请求或使用新动画的关键帧创建问题,我们总是很高兴能有更多动画!🆒
我们可以设置动画属性来none
清除前一个动画的关键帧。
这里还列出了最常见的缓动函数📈
我们可以将缓动属性设置为自定义函数,例如cubic-bezier(0.25, 0.1, 0.25, 1)
,该值等于ease
。
这里的神奇之处在于,您可以使用属性/属性自定义元素的每个动画的持续时间、延迟、迭代次数和 Web 动画 API 的任何其他配置,并且我们可以添加新的酷炫动画,因为这非常简单和性感,感谢 TypeScript!
框架集成
好的,它与 HTML 元素配合使用看起来很棒,但是……我该如何使用它从Angular、React、Vue等组件中获取另一个组件?🤔
该 Web 组件是使用StencilJS创建的,因此集成该组件非常容易:
角度
<animatable-component autoplay [animation]="myAnimation" [duration]="300">
<h1>Animate it</h1>
</animatable-component>
反应
- 全局导入 Web 组件,请点击此处。
- 使用组件
<animatable-component autoplay animation={myAnimation} duration={300}>
<h1>Animate it</h1>
</animatable-component>
Vue
- 全局导入 Web 组件,请点击此处。
- 使用组件
<animatable-component autoplay v-bind:animation.prop="myAnimation" duration="300">
<h1>Animate it</h1>
</animatable-component>
正如你所见,我们这里有通用组件,太棒了!👏
额外奖励:使用 StencilJS 的高阶组件(HOC)
重用 React 逻辑的最佳策略之一是使用HOC,通过这种方式我们可以扩展行为、重用组件并改善代码的维护✍️。
使用 StencilJS 也可以将这个概念与函数组件一起使用!🙌
function createAnimatableComponent (
WrappedComponent: FunctionalComponent
) {
return (props) => {
const { keyFrames, options, onFinish, ...rest } = props
return (
<animatable-component
keyFrames={keyFrames}
options={options}
onFinish={onFinish}
>
<WrappedComponent {...rest} />
</animatable-component>
)
}
};
想看一个使用类型的示例吗?点击此处查看Animatable 中的实用函数!使用createAnimatableComponent HOC,你可以创建自己的组件,并用Animatable简单包装它们,从而共享通用逻辑并为多个组件设置动画!👽
在此处查看其他好的例子。
我希望您发现这个组件对您的项目有用,让我们继续使用 StencilJS 改进我们的通用组件,在这里查看更多资源!😊
支持🍻
我相信独角兽🦄如果您也相信的话,请支持我。
用❤️制作
胡安·D·尼科尔斯
文章来源:https://dev.to/jdnichollsc/meet-animatable-a-tiny-web-component-to-use-web-animations-api-as-a-component-1glh