• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.animator (Animator)
2
3The **Animator** module provides APIs for applying animation effects, including defining animations, starting animations, and playing animations in reverse order.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8>
9> This module can be used in ArkTS since API version 9.
10>
11> This module cannot be used in the file declaration of the [UIAbility](./js-apis-app-ability-uiAbility.md). In other words, the APIs of this module can be used only after a component instance is created; they cannot be called in the lifecycle of the UIAbility.
12>
13> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext).
14>
15> Since API version 10, you can use the [createAnimator](./js-apis-arkui-UIContext.md#createanimator) API in [UIContext](./js-apis-arkui-UIContext.md#uicontext) to obtain the UI context.
16
17## Modules to Import
18
19```ts
20import animator, { AnimatorOptions,AnimatorResult } from '@ohos.animator';
21```
22## create<sup>9+</sup>
23
24create(options: AnimatorOptions): AnimatorResult
25
26Creates an **Animator** object.
27
28**System capability**: SystemCapability.ArkUI.ArkUI.Full
29
30**Parameters**
31
32| Name    | Type                                 | Mandatory  | Description     |
33| ------- | ----------------------------------- | ---- | ------- |
34| options | [AnimatorOptions](#animatoroptions) | Yes   | Animator options.|
35
36**Return value**
37
38| Type                               | Description           |
39| --------------------------------- | ------------- |
40| [AnimatorResult](#animatorresult) | Animator result.|
41
42**Example**
43
44  ```ts
45import animator, { AnimatorOptions,AnimatorResult } from '@ohos.animator';
46let options: AnimatorOptions = {
47   duration: 1500,
48   easing: "friction",
49   delay: 0,
50   fill: "forwards",
51   direction: "normal",
52   iterations: 3,
53   begin: 200.0,
54   end: 400.0
55};
56animator.create(options);
57  ```
58
59## AnimatorResult
60
61Defines the animator result.
62
63### reset<sup>9+</sup>
64
65reset(options: AnimatorOptions): void
66
67Updates this animator.
68
69**System capability**: SystemCapability.ArkUI.ArkUI.Full
70
71**Parameters**
72
73| Name    | Type                                 | Mandatory  | Description     |
74| ------- | ----------------------------------- | ---- | ------- |
75| options | [AnimatorOptions](#animatoroptions) | Yes   | Animator options.|
76
77**Error codes**
78
79For details about the error codes, see [Animator Error Codes](../errorcodes/errorcode-animator.md).
80
81| ID  | Error Message|
82| --------- | ------- |
83| 100001    | if no page is found for pageId or fail to get object property list. |
84
85
86**Example**
87
88```ts
89import animator, { AnimatorOptions,AnimatorResult } from '@ohos.animator';
90import { BusinessError } from '@ohos.base';
91let options: AnimatorOptions = {
92  duration: 1500,
93  easing: "friction",
94  delay: 0,
95  fill: "forwards",
96  direction: "normal",
97  iterations: 3,
98  begin: 200.0,
99  end: 400.0
100};
101let optionsNew: AnimatorOptions = {
102  duration: 1500,
103  easing: "friction",
104  delay: 0,
105  fill: "forwards",
106  direction: "normal",
107  iterations: 5,
108  begin: 200.0,
109  end: 400.0
110};
111try {
112  let animatorResult:AnimatorResult|undefined = animator.create(options)
113  animatorResult.reset(optionsNew);
114} catch(error) {
115  let message = (error as BusinessError).message
116  let code = (error as BusinessError).code
117  console.error(`Animator reset failed, error code: ${code}, message: ${message}.`);
118}
119```
120
121### play
122
123play(): void
124
125Plays this animation. The animation retains the previous playback state. For example, if the animation is set to **reverse** and paused, it will remain in **reverse** when resumed.
126
127**System capability**: SystemCapability.ArkUI.ArkUI.Full
128
129**Example**
130
131```ts
132animator.play();
133```
134
135### finish
136
137finish(): void
138
139Ends this animation.
140
141**System capability**: SystemCapability.ArkUI.ArkUI.Full
142
143**Example**
144
145```ts
146animator.finish();
147```
148
149### pause
150
151pause(): void
152
153Pauses this animation.
154
155**System capability**: SystemCapability.ArkUI.ArkUI.Full
156
157**Example**
158
159```ts
160animator.pause();
161```
162
163### cancel
164
165cancel(): void
166
167Cancels this animation.
168
169**System capability**: SystemCapability.ArkUI.ArkUI.Full
170
171**Example**
172
173```ts
174animator.cancel();
175```
176
177### reverse
178
179reverse(): void
180
181Plays this animation in reverse order. This API does not take effect when the interpolating spring curve is used.
182
183**System capability**: SystemCapability.ArkUI.ArkUI.Full
184
185**Example**
186
187```ts
188animator.reverse();
189```
190
191### onframe
192
193onframe: (progress: number) => void
194
195Called when a frame is received.
196
197**System capability**: SystemCapability.ArkUI.ArkUI.Full
198
199**Parameters**
200
201| Name     | Type    | Mandatory  | Description      |
202| -------- | ------ | ---- | -------- |
203| progress | number | Yes   | Current progress of the animation.|
204
205**Example**
206
207```ts
208import animator, { AnimatorResult } from '@ohos.animator';
209let animatorResult:AnimatorResult|undefined = animator.create(options)
210animatorResult.onframe = (value)=> {
211  console.info("onframe callback")
212}
213```
214
215### onfinish
216
217onfinish: () => void
218
219Called when this animation is finished.
220
221**System capability**: SystemCapability.ArkUI.ArkUI.Full
222
223**Example**
224
225```ts
226import animator, { AnimatorResult } from '@ohos.animator';
227let animatorResult:AnimatorResult|undefined = animator.create(options)
228animatorResult.onfinish = ()=> {
229  console.info("onfinish callback")
230}
231```
232
233### oncancel
234
235oncancel: () => void
236
237Called when this animation is canceled.
238
239**System capability**: SystemCapability.ArkUI.ArkUI.Full
240
241**Example**
242
243```ts
244import animator, { AnimatorResult } from '@ohos.animator';
245let animatorResult:AnimatorResult|undefined = animator.create(options)
246animatorResult.oncancel = ()=> {
247  console.info("oncancel callback")
248}
249```
250
251### onrepeat
252
253onrepeat: () => void
254
255Called when this animation repeats.
256
257**System capability**: SystemCapability.ArkUI.ArkUI.Full
258
259**Example**
260
261```ts
262import animator, { AnimatorResult } from '@ohos.animator';
263let animatorResult:AnimatorResult|undefined = animator.create(options)
264animatorResult.onrepeat = ()=> {
265  console.info("onrepeat callback")
266}
267```
268
269
270
271## AnimatorOptions
272
273Defines animator options.
274
275**System capability**: SystemCapability.ArkUI.ArkUI.Full
276
277| Name      | Type                                                       | Mandatory| Description                                                        |
278| ---------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
279| duration   | number                                                      | Yes  | Duration for playing the animation, in milliseconds.<br>Default value: **0**                                  |
280| easing     | string                                                      | Yes  | Animation interpolation curve. Only the following values are supported:<br>**"linear"**: The animation speed keeps unchanged.<br>**"ease"**: The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used.<br>**"ease-in"**: The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used.<br>**"ease-out"**: The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used.<br>**"ease-in-out"**: The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.<br>**"fast-out-slow-in"**: The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0).<br>**"linear-out-slow-in"**: The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0).<br>**"fast-out-linear-in"**: The animation uses acceleration cubic-bezier curve (0.4, 0.0, 1.0, 1.0)<br>**"friction"**: The animation uses the damping cubic-bezier curve (0.2, 0.0, 0.2, 1.0).<br>**"extreme-deceleration"**: The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0).<br>**"rhythm"**: The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0).<br>**"sharp"**: The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0).<br>**"smooth"**: The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0).<br>**"cubic-bezier(x1,y1,x2,y2)"**: The animation uses the defined cubic bezier curve, where the value of **x1** and **x2** must range from 0 to 1. For example, **"cubic-bezier(0.42,0.0,0.58,1.0)"**.<br>**"steps(number,step-position)"**: The animation uses a step curve. The **number** parameter is mandatory and must be set to a positive integer. The **step-position** parameter is optional and can be set to **start** or **end** (default value). For example, **"steps(3,start)"**.<br>**"interpolating-spring(velocity,mass,stiffness,damping)"**: The animation uses an interpolating spring curve. This API is supported since API version 11 and can be used only in ArkTS. The **velocity**, **mass**, **stiffness**, and **damping** parameters are of the numeric type, and the values of **mass**, **stiffness**, and **damping** must be greater than 0. For details about the parameters, see [Curves.interpolatingSpring](./js-apis-curve.md#curvesinterpolatingspring10). When an interpolating spring curve is used, settings for the **duration**, **fill**, **direction**, and **iterations** do not take effect. Rather, the value of **duration** is subject to the spring settings, **fill** is fixed at **forwards**, **direction** at **normal**, and **iterations** at **1**. In addition, invoking [reverse](#reverse) of **animator** is not effective. In other words, when using an interpolating spring curve, the animation can play only once in forward mode.|
281| delay      | number                                                      | Yes  | Animation delay duration, in milliseconds. Value **0** means that there is no delay.         |
282| fill       | "none" \| "forwards" \| "backwards" \| "both"               | Yes  | State of the animated target after the animation is executed.<br>**"none"**: No style is applied to the target before or after the animation is executed.<br>**"forwards"**: The target keeps the state at the end of the animation (defined in the last key frame) after the animation is executed.<br>**"backwards"**: The animation uses the value defined in the first key frame during the **animation-delay**. When **animation-direction** is set to **normal** or **alternate**, the value in the **from** key frame is used. When **animation-direction** is set to **reverse** or **alternate-reverse**, the value in the **to** key frame is used.<br>**"both"**: The animation follows the **forwards** and **backwards** rules.|
283| direction  | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes  | Animation playback mode.<br>**"normal"**: plays the animation in forward loop mode.<br>**"reverse"**: plays the animation in reverse loop mode.<br>**"alternate"**: plays the animation in alternating loop mode. When the animation is played for an odd number of times, the playback is in forward direction. When the animation is played for an even number of times, the playback is in reverse direction.<br>**"alternate-reverse"**: plays the animation in reverse alternating loop mode. When the animation is played for an odd number of times, the playback is in reverse direction. When the animation is played for an even number of times, the playback is in forward direction.<br>Default value: **'normal'**|
284| iterations | number                                                      | Yes  | Number of times that the animation is played. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times.<br>**NOTE**<br>If this parameter is set to a negative value other than **-1**, the value is invalid. In this case, the animation is played once.|
285| begin      | number                                                      | Yes  | Start point of the animation interpolation.<br>Default value: **1**                                              |
286| end        | number                                                      | Yes  | End point of animation interpolation.<br>Default value: **1**                                              |
287
288
289## Example
290### JavaScript-compatible Web-like Development Paradigm
291
292```html
293<!-- hml -->
294<div class="container">
295  <div class="Animation" style="height: {{divHeight}}px; width: {{divWidth}}px; background-color: red;" onclick="Show">
296  </div>
297</div>
298```
299
300```ts
301import animator, { AnimatorOptions,AnimatorResult } from '@ohos.animator';
302import { BusinessError } from '@ohos.base';
303let DataTmp:Record<string,animator> = {
304  'divWidth': 200,
305  'divHeight': 200,
306  'animator': animator
307}
308class Tmp{
309  data:animator = DataTmp
310  onInit:Function = ()=>{}
311  Show:Function = ()=>{}
312}
313class DateT{
314  divWidth:number = 0
315  divHeight:number = 0
316  animator:AnimatorResult | null = null
317}
318(Fn:(v:Tmp) => void) => {Fn({
319  data: DataTmp,
320  onInit() {
321    let options:AnimatorOptions = {
322      duration: 1500,
323      easing: "friction",
324      delay: 0,
325      fill: "forwards",
326      direction: "normal",
327      iterations: 2,
328      begin: 200.0,
329      end: 400.0
330    };
331    let DataTmp:DateT = {
332      divWidth: 200,
333      divHeight: 200,
334      animator: null
335    }
336    DataTmp.animator = animator.create(options);
337  },
338  Show() {
339    let options1:AnimatorOptions = {
340      duration: 1500,
341      easing: "friction",
342      delay: 0,
343      fill: "forwards",
344      direction: "normal",
345      iterations: 2,
346      begin: 0,
347      end: 400.0,
348    };
349    let DataTmp:DateT = {
350      divWidth: 200,
351      divHeight: 200,
352      animator: null
353    }
354    try {
355      DataTmp.animator = animator.create(options1);
356      DataTmp.animator.reset(options1);
357    } catch(error) {
358      let message = (error as BusinessError).message
359      let code = (error as BusinessError).code
360      console.error(`Animator reset failed, error code: ${code}, message: ${message}.`);
361    }
362    let _this = DataTmp;
363    if(DataTmp.animator){
364      DataTmp.animator.onframe = (value:number)=> {
365        _this.divWidth = value;
366        _this.divHeight = value;
367      };
368      DataTmp.animator.play();
369    }
370  }
371})}
372```
373
374  ![en-us_image_00007](figures/en-us_image_00007.gif)
375
376### ArkTS-based Declarative Development Paradigm
377
378```ts
379import animator, { AnimatorResult } from '@ohos.animator';
380
381@Entry
382@Component
383struct AnimatorTest {
384  private TAG: string = '[AnimatorTest]'
385  private backAnimator: AnimatorResult | undefined = undefined
386  private flag: boolean = false
387  @State wid: number = 100
388  @State hei: number = 100
389
390  create() {
391    let _this = this
392    this.backAnimator = animator.create({
393      duration: 2000,
394      easing: "ease",
395      delay: 0,
396      fill: "forwards",
397      direction: "normal",
398      iterations: 1,
399      begin: 100,
400      end: 200
401    })
402    this.backAnimator.onfinish = ()=> {
403      _this.flag = true
404      console.info(_this.TAG, 'backAnimator onfinish')
405    }
406    this.backAnimator.onrepeat = ()=> {
407      console.info(_this.TAG, 'backAnimator repeat')
408    }
409    this.backAnimator.oncancel = ()=> {
410      console.info(_this.TAG, 'backAnimator cancel')
411    }
412    this.backAnimator.onframe = (value:number)=> {
413      _this.wid = value
414      _this.hei = value
415    }
416  }
417
418  aboutToDisappear() {
419    // Because backAnimator references this in onframe, backAnimator is saved in this.
420    // When the custom component disappears, leave backAnimator empty to avoid memory leak.
421    this.backAnimator = undefined;
422  }
423
424  build() {
425    Column() {
426      Column() {
427        Column()
428          .width(this.wid)
429          .height(this.hei)
430          .backgroundColor(Color.Red)
431      }
432      .width('100%')
433      .height(300)
434
435      Column() {
436        Row() {
437          Button('create')
438            .fontSize(30)
439            .fontColor(Color.Black)
440            .onClick(() => {
441              this.create()
442            })
443        }
444        .padding(10)
445
446        Row() {
447          Button('play')
448            .fontSize(30)
449            .fontColor(Color.Black)
450            .onClick(() => {
451              this.flag = false
452              if(this.backAnimator){
453                this.backAnimator.play()
454              }
455            })
456        }
457        .padding(10)
458
459        Row() {
460          Button('pause')
461            .fontSize(30)
462            .fontColor(Color.Black)
463            .onClick(() => {
464              if(this.backAnimator){
465                this.backAnimator.pause()
466              }
467            })
468        }
469        .padding(10)
470
471        Row() {
472          Button('finish')
473            .fontSize(30)
474            .fontColor(Color.Black)
475            .onClick(() => {
476              this.flag = true
477              if(this.backAnimator){
478                this.backAnimator.finish()
479              }
480            })
481        }
482        .padding(10)
483
484        Row() {
485          Button('reverse')
486            .fontSize(30)
487            .fontColor(Color.Black)
488            .onClick(() => {
489              this.flag = false
490              if(this.backAnimator){
491                this.backAnimator.reverse()
492              }
493            })
494        }
495        .padding(10)
496
497        Row() {
498          Button('cancel')
499            .fontSize(30)
500            .fontColor(Color.Black)
501            .onClick(() => {
502              if(this.backAnimator){
503                this.backAnimator.cancel()
504              }
505            })
506        }
507        .padding(10)
508
509        Row() {
510          Button('reset')
511            .fontSize(30)
512            .fontColor(Color.Black)
513            .onClick(() => {
514              if (this.flag) {
515                this.flag = false
516                if(this.backAnimator){
517                  this.backAnimator.reset({
518                    duration: 3000,
519                    easing: "ease-in",
520                    delay: 0,
521                    fill: "forwards",
522                    direction: "alternate",
523                    iterations: 3,
524                    begin: 100,
525                    end: 300
526                  })
527                }
528              } else {
529                console.info(this.TAG, 'Animation not ended')
530              }
531            })
532        }
533        .padding(10)
534      }
535    }
536  }
537}
538```
539
540## update<sup>(deprecated)</sup>
541
542update(options: AnimatorOptions): void
543
544Updates this animator.
545
546This API is deprecated since API version 9. You are advised to use [reset<sup>9+</sup>](#reset9) instead.
547
548**System capability**: SystemCapability.ArkUI.ArkUI.Full
549
550**Parameters**
551
552| Name    | Type                                 | Mandatory  | Description     |
553| ------- | ----------------------------------- | ---- | ------- |
554| options | [AnimatorOptions](#animatoroptions) | Yes   | Animator options.|
555
556**Example**
557
558```ts
559animator.update(options);
560```
561
562## createAnimator<sup>(deprecated)</sup>
563
564createAnimator(options: AnimatorOptions): AnimatorResult
565
566Creates an **Animator** object.
567
568This API is deprecated since API version 9. You are advised to use [create<sup>9+</sup>](#create9) instead.
569
570**System capability**: SystemCapability.ArkUI.ArkUI.Full
571
572**Parameters**
573
574| Name    | Type                                 | Mandatory  | Description     |
575| ------- | ----------------------------------- | ---- | ------- |
576| options | [AnimatorOptions](#animatoroptions) | Yes   | Animator options.|
577
578**Return value**
579
580| Type                               | Description           |
581| --------------------------------- | ------------- |
582| [AnimatorResult](#animatorresult) | Animator result.|
583
584**Example**
585
586```ts
587import animator, { AnimatorOptions,AnimatorResult } from '@ohos.animator';
588let options: AnimatorOptions = { // The explicit type AnimatorOptions does not need to be emphasized in a .js file.
589  duration: 1500,
590  easing: "friction",
591  delay: 0,
592  fill: "forwards",
593  direction: "normal",
594  iterations: 3,
595  begin: 200.0,
596  end: 400.0,
597};
598this.animator = animator.createAnimator(options);
599```
600