使用 Motion One 为你的 Angular 应用制作动画
Motion One是一个基于 Web Animations API 构建的全新动画库。如果您之前使用过 Popmotion 或 Greensock,那么这个库的语法应该非常熟悉。
在这篇博文中,我将向您展示如何在 Angular 应用程序中使用 Motion One。我将指导您完成安装过程、创建一个简单的动画,并使用 Motion One 的弹簧和时间轴功能。
查看我创建的现场演示,您可以将其作为我的Angular Animation Explorer 的一部分进行交互。
开始
首先,我们需要使用以下命令通过 npm 添加 Motion One 的依赖项。
npm install --save motion
如果您在库中遇到任何类型问题,请尝试添加
skipLibCheck: true
到您的 tsconfig.json。
使用 Motion One 进行基本动画
要为模板中的元素设置动画,您需要为其指定一个 id,以便可以从 Typescript 文件访问它们。
<div #myElement>...</div>
然后您可以使用 Angular 的ViewChild
装饰器来访问上面定义的元素。
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
...
})
export class MotionOneDemoComponent {
@ViewChild('myElement') myElement: ElementRef;
}
现在我们可以访问您的元素,您可以使用 Motion One 的动画 API 为您的元素制作动画。
import { Component, ViewChild, ElementRef } from '@angular/core';
import { animate } from 'motion';
@Component({
...
})
export class MotionOneDemoComponent {
@ViewChild('myElement') myElement: ElementRef;
animateMyElement(): void {
animate(
this.myElement.nativeElement,
{ rotate: 180 },
{ duration: 0.5, easing: 'ease-in' }
).finished.then(() => {
// animation completed
})
.catch(() => {
// if an error happens
});
}
}
弹簧和滑行动画
Motion One 还预置了缓动函数,例如spring
和glide
which,您可以通过传入相应的函数并添加其他配置来使用它们。以下代码片段展示了如何使用 Motion One 创建基本的弹簧动画:
import { Component, ViewChild, ElementRef } from '@angular/core';
import { animate, spring } from 'motion';
@Component({
...
})
export class MotionOneDemoComponent {
@ViewChild('myElement') myElement: ElementRef;
animateMyElement(): void {
animate(
this.myElement.nativeElement,
{ rotate: 180 },
{ duration: 0.5, easing: spring() } // 👈 modify the easing
).finished.then(() => {
// animation completed
})
.catch(() => {
// if an error happens
});
}
}
时间轴动画
Motion One 的另一个很酷的功能是它开箱即用的时间轴支持。你可以创建一个动画数组并将其传递给函数,从而串联多个动画并同时为不同的元素添加动画效果timeline
。
该timeline
函数的工作原理与 Greensock 的时间轴功能类似。下面的代码片段展示了如何链接和排序一个框的翻译。
import { Component, ViewChild, ElementRef } from '@angular/core';
import { timeline } from 'motion';
@Component({
...
})
export class MotionOneDemoComponent {
@ViewChild('myElement') myElement: ElementRef;
animateMyElement(): void {
const sequence = [
[this.myElement.nativeElement, { x: 100 }, { duration: 0.5 }],
[this.myElement.nativeElement, { y: 100 }, { duration: 0.5 }],
[this.myElement.nativeElement, { x: 0, y: 0 }, { duration: 1 }],
];
timeline(sequence)
.finished.then(() => {
// animation completed
})
.catch(() => {
// if an error happens
});
}
}
总结
与其他动画库相比,Motion One 是一个相对较新的动画库。然而,它功能丰富、性能卓越且易于使用。这篇博文仅涵盖了该库一小部分的功能。我将在未来探索 Motion One 的更多功能,并撰写一篇后续博文,介绍该库的更多高级用法。
如果您对更多此类内容感兴趣或有任何疑问,请在评论中告诉我或在推特上@williamjuan27
鏂囩珷鏉ユ簮锛�https://dev.to/this-is-angular/animate-your-angular-app-using-motion-one-4bg3