Skip to main content

动画

概述

¥Overview

Ionic Animations 是一种工具,使开发者能够以与平台无关的方式创建复杂的动画,而不需要特定的框架或 Ionic 应用。

¥Ionic Animations is a tool that enables developers to create complex animations in a platform-agnostic manner, without requiring a specific framework or an Ionic app.

创建高效的动画可能具有挑战性,因为开发者受到设备的可用库和硬件资源的限制。而且,许多动画库使用 JavaScript 驱动的方法,这会降低动画的可扩展性并占用 CPU 时间。

¥Creating efficient animations can be challenging, as developers are limited by the available libraries and hardware resources of the device. Moreover, many animation libraries use a JavaScript-driven approach, which can reduce the scalability of animations and use up CPU time.

另一方面,Ionic Animations 使用 网页动画 API,它将动画的所有计算和运行卸载到浏览器。这种方法允许浏览器优化动画并确保其顺利执行。在不支持 Web 动画的情况下,Ionic 动画将回退到 CSS 动画,这在性能上的差异应该可以忽略不计。

¥Ionic Animations, on the other hand, uses the Web Animations API, which offloads all the computation and running of animations to the browser. This approach allows the browser to optimize the animations and ensure their smooth execution. In cases where Web Animations are not supported, Ionic Animations will fall back to CSS Animations, which should have a negligible difference in performance.

安装

¥Installation

Developers using Ionic Core and JavaScript should install the latest version of @ionic/core.

import { createAnimation } from 'https://cdn.jsdelivr.net/npm/@ionic/core@latest/dist/esm/index.mjs';

...

const animation = createAnimation()
.addElement(myElementRef)
.duration(1000)
.fromTo('opacity', '1', '0.5');
}

基本动画

¥Basic Animations

在下面的示例中,创建了一个动画,用于更改 ion-card 元素的不透明度并沿 X 轴从左向右移动它。该动画将运行无限次,每次动画迭代将持续 1500 毫秒。

¥In the example below, an animation that changes the opacity on the ion-card element and moves it from left to right along the X axis has been created. This animation will run an infinite number of times, and each iteration of the animation will last 1500ms.

默认情况下,所有 Ionic 动画都会暂停,直到调用 play 方法。

¥By default, all Ionic Animations are paused until the play method is called.

关键帧动画

¥Keyframe Animations

Ionic Animations 允许你使用关键帧控制动画中的中间步骤。此处可以使用任何有效的 CSS 属性,你甚至可以使用 CSS 变量作为值。

¥Ionic Animations allows you to control the intermediate steps in an animation using keyframes. Any valid CSS property can be used here, and you can even use CSS Variables as values.

编写关键帧时,应使用驼峰式大小写来编写带连字符的 CSS 属性。例如,border-radius 应写为 borderRadius。这也适用于 fromTo()from(),to() 方法。

¥Hyphenated CSS properties should be written using camel case when writing keyframes. For example, border-radius should be written as borderRadius. This also applies to the fromTo(), from(), and to() methods.

在上面的示例中,卡片元素将从其初始宽度过渡到由 --width 变量定义的宽度,然后过渡到最终宽度。

¥In the example above, the card element will transition from its initial width, to a width defined by the --width variable, and then transition on to the final width.

每个关键帧对象都包含一个 offset 属性。offset 是一个介于 0 和 1 之间的值,用于定义关键帧步长。偏移值必须按升序排列且不能重复。

¥Each keyframe object contains an offset property. offset is a value between 0 and 1 that defines the keyframe step. Offset values must go in ascending order and cannot repeat.

分组动画

¥Grouped Animations

可以同时对多个元素进行动画处理并通过单个父动画对象进行控制。除非另有指定,子动画继承持续时间、缓动和迭代等属性。在所有子动画完成之前,不会调用父动画的 onFinish 回调。

¥Multiple elements can be animated at the same time and controlled via a single parent animation object. Child animations inherit properties such as duration, easing, and iterations unless otherwise specified. A parent animation's onFinish callback will not be called until all child animations have completed.

此示例显示由单个父动画控制的 3 个子动画。动画 cardAcardB 继承父动画的 2000 毫秒持续时间,但动画 cardC 的持续时间为 5000 毫秒,因为它是显式设置的。

¥This example shows 3 child animations controlled by a single parent animation. Animations cardA and cardB inherit the parent animation's duration of 2000ms, but animation cardC has a duration of 5000ms since it was explicitly set.

钩子之前和之后

¥Before and After Hooks

Ionic Animations 提供了一些钩子,让你可以在动画运行之前和动画完成之后更改元素。这些钩子可用于执行 DOM 读取和写入以及添加或删除类和内联样式。

¥Ionic Animations provides hooks that let you alter an element before an animation runs and after an animation completes. These hooks can be used to perform DOM reads and writes as well as add or remove classes and inline styles.

此示例设置一个内联过滤器,该过滤器在动画开始之前将卡片的背景颜色反转 75%。动画完成后,元素上的框阴影将设置为 rgba(255, 0, 50, 0.4) 0px 4px 16px 6px,发出红色光芒,并且内联过滤器将被清除。必须停止动画才能删除框阴影并再次使用滤镜播放。

¥This example sets an inline filter which inverts the background color of the card by 75% prior to the animation starting. Once the animation finishes, the box shadow on the element is set to rgba(255, 0, 50, 0.4) 0px 4px 16px 6px, a red glow, and the inline filter is cleared. The animation must be stopped in order to remove the box shadow and play it with the filter again.

有关钩子的完整列表,请参阅 方法

¥See Methods for a complete list of hooks.

连锁动画

¥Chained Animations

动画可以链接起来一个接一个地运行。play 方法返回一个 Promise,该 Promise 在动画完成时解析。

¥Animations can be chained to run one after the other. The play method returns a Promise that resolves when the animation has completed.

手势动画

¥Gesture Animations

Ionic Animations 使开发者能够通过与 Ionic 手势 无缝集成来创建强大的基于手势的动画。

¥Ionic Animations gives developers the ability to create powerful gesture-based animations by integrating seamlessly with Ionic Gestures.

在下面的示例中,我们将创建一条轨道,我们可以沿着该轨道拖动卡片元素。我们的 animation 对象将负责向左或向右移动卡片元素,而我们的 gesture 对象将指示 animation 对象向哪个方向移动。

¥In the following example we are creating a track along which we can drag the card element. Our animation object will take care of moving the card element either left or right, and our gesture object will instruct the animation object which direction to move in.

基于偏好的动画

¥Preference-Based Animations

开发者还可以使用 CSS 变量根据用户偏好定制动画,例如 prefers-reduced-motionprefers-color-scheme

¥Developers can also tailor their animations to user preferences such as prefers-reduced-motion and prefers-color-scheme using CSS Variables.

首次创建动画时,此方法适用于所有支持的浏览器。大多数浏览器还能够随着 CSS 变量的变化动态更新关键帧动画。

¥This method works in all supported browsers when creating animations for the first time. Most browsers are also capable of dynamically updating keyframe animations as the CSS Variables change.

Safari 目前不支持动态更新关键帧动画。对于在 Safari 中需要这种支持的开发者,他们可以使用 MediaQueryList.addListener()

¥Safari does not currently support dynamically updating keyframe animations. For developers who need this kind of support in Safari, they can use MediaQueryList.addListener().

覆盖 Ionic 组件动画

¥Overriding Ionic Component Animations

某些 Ionic 组件允许开发者提供自定义动画。所有动画都作为组件上的属性提供或通过全局配置设置。

¥Certain Ionic components allow developers to provide custom animations. All animations are provided as either properties on the component or are set via a global config.

模态

¥Modals

性能考虑因素

¥Performance Considerations

CSS 和 Web 动画通常在合成器线程上处理。这与执行布局、绘画、样式和 JavaScript 的主线程不同。建议你更喜欢使用可以在合成器线程上处理的属性,以获得最佳动画性能。

¥CSS and Web Animations are usually handled on the compositor thread. This is different than the main thread where layout, painting, styling, and your JavaScript is executed. It is recommended that you prefer using properties that can be handled on the compositor thread for optimal animation performance.

heightwidth 等动画属性会导致额外的布局和绘制,从而导致卡顿并降低动画性能。另一方面,诸如 transformopacity 之类的动画属性可由浏览器高度优化,并且通常不会导致太多卡顿。

¥Animating properties such as height and width cause additional layouts and paints which can cause jank and degrade animation performance. On the other hand, animating properties such as transform and opacity are highly optimizable by the browser and typically do not cause much jank.

有关哪些 CSS 属性导致布局或绘制发生的信息,请参阅 CSS 触发器

¥For information on which CSS properties cause layouts or paints to occur, see CSS Triggers.

调试

¥Debugging

对于在 Chrome 中调试动画,有一篇关于使用 Chrome DevTools 检查动画的精彩博客文章:https://developers.google.com/web/tools/chrome-devtools/inspect-styles/animations

¥For debugging animations in Chrome, there is a great blog post about inspecting animations using the Chrome DevTools: https://developers.google.com/web/tools/chrome-devtools/inspect-styles/animations.

还建议为你的动画分配唯一的标识符。这些标识符将显示在 Chrome 的动画检查器中,并且应该更容易调试:

¥It is also recommended to assign unique identifiers to your animations. These identifiers will show up in the Animations inspector in Chrome and should make it easier to debug:

/**

* The animation for the .square element should

* show "my-animation-identifier" in Chrome DevTools.
*/
const animation = createAnimation('my-animation-identifier')
.addElement(document.querySelector('.square'))
.duration(1000)
.fromTo('opacity', '1', '0');

API

本节提供 Animation 类上所有可用方法和属性的列表。

¥This section provides a list of all the methods and properties available on the Animation class.

接口

¥Interfaces

AnimationDirection

type AnimationDirection = 'normal' | 'reverse' | 'alternate' | 'alternate-reverse';

AnimationFill

type AnimationFill = 'auto' | 'none' | 'forwards' | 'backwards' | 'both';

AnimationBuilder

type AnimationBuilder = (baseEl: any, opts?: any) => Animation;
注意

opts 是特定于自定义动画的附加选项。例如,工作表模式输入动画包含当前断点的信息。

¥opts are additional options that are specific to the custom animation. For example, the sheet modal enter animation includes information for the current breakpoint.

AnimationCallbackOptions

interface AnimationCallbackOptions {
/**

* If true, the associated callback will only be fired once.
*/
oneTimeCallback: boolean;
}

AnimationPlayOptions

interface AnimationPlayOptions {
/**

* If true, the animation will play synchronously.

* This is the equivalent of running the animation

* with a duration of 0ms.
*/
sync: boolean;
}

属性

¥Properties

名称描述
childAnimations: Animation[]给定父动画的所有子动画。
elements: HTMLElement[]附加到动画的所有元素。
parentAnimation?: Animation给定动画对象的父动画。

方法

¥Methods

名称描述
addAnimation(animationToAdd: Animation | Animation[]): Animation将一个或多个动画组合在一起以由父动画控制。
addElement(el: Element | Element[] | Node | Node[] | NodeList): Animation向动画添加一个或多个元素。
afterAddClass(className: string | string[]): Animation添加要在动画结束后添加到动画中的所有元素的类或类数组。
afterAddRead(readFn: (): void): Animation添加一个执行 DOM 读取的函数,以便在动画结束后运行。
afterAddWrite(writeFn: (): void): Animation添加一个执行 DOM 写入的函数,以便在动画结束后运行。
afterClearStyles(propertyNames: string[]): Animation添加属性名称数组,以便在动画结束后从动画中所有元素的内联样式中清除。
afterRemoveClass(className: string | string[]): Animation添加要在动画结束后从动画中的所有元素中删除的类或类数组。
afterStyles(styles: { [property: string]: any }): Animation添加要在动画结束后应用于动画中所有元素的样式对象。
beforeAddClass(className: string | string[]): Animation在动画开始之前添加要添加到动画中所有元素的类或类数组。
beforeAddRead(readFn: (): void): Animation添加一个在动画开始之前执行 DOM 读取的函数。
beforeAddWrite(writeFn: (): void): Animation添加一个在动画开始之前执行 DOM 写入的函数。
beforeClearStyles(propertyNames: string[]): Animation添加要在动画开始之前从动画中所有元素的内联样式中清除的属性名称数组。
beforeRemoveClass(className: string | string[]): Animation添加要在动画开始之前从动画中的所有元素中删除的类或类数组。
beforeStyles(styles: { [property: string]: any }): Animation在动画开始之前添加要应用于动画中所有元素的样式对象。
direction(direction?: AnimationDirection): Animation设置动画播放的方向。
delay(delay?: number): Animation设置动画开始的延迟(以毫秒为单位)。
destroy(clearStyleSheets?: boolean): Animation销毁动画并清除所有元素、子动画和关键帧。
duration(duration?: number): Animation设置动画的持续时间(以毫秒为单位)。
easing(easing?: string): Animation设置动画的缓动(以毫秒为单位)。有关可接受的缓动值的列表,请参阅 缓和效果
from(property: string, value: any): Animation设置动画的开始样式。
fromTo(property: string, fromValue: any, toValue: any): Animation设置动画的开始和结束样式。
fill(fill?: AnimationFill): Animation设置动画在执行之前和之后如何将样式应用于其元素。
iterations(iterations: number): Animation设置动画循环在停止之前应播放的次数。
keyframes(keyframes: any[]): Animation设置动画的关键帧。
onFinish(callback: (didComplete: boolean, animation: Animation): void, opts?: AnimationCallbackOptions): Animation添加要在动画结束时运行的回调。
pause(): Animation暂停动画。
play(opts?: AnimationPlayOptions): Promise<void>播放动画。
progressEnd(playTo?: 0 | 1, step: number, dur?: number): Animation停止通过动画寻找。
progressStart(forceLinearEasing?: boolean, step?: number): Animation开始通过动画寻找。
progressStep(step: number): Animation通过动画寻找。
stop(): Animation停止动画并将所有元素重置为其初始状态。
to(property: string, value: any): Animation设置动画的结束样式。