js-apis-animator.md 16.2 KB
Newer Older
E
ester.zhou 已提交
1
# @ohos.animator (Animator)
E
esterzhou 已提交
2

E
ester.zhou 已提交
3
The **Animator** module provides APIs for applying animation effects, including defining animations, starting animations, and playing animations in reverse order.
E
ester.zhou 已提交
4

E
ester.zhou 已提交
5 6
> **NOTE**
>
E
ester.zhou 已提交
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.
E
ester.zhou 已提交
8
>
E
ester.zhou 已提交
9
> 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.
E
ester.zhou 已提交
10 11 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).
>
> 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.
Z
zengyawen 已提交
14

15
## Modules to Import
Z
zengyawen 已提交
16

E
esterzhou 已提交
17
```js
E
ester.zhou 已提交
18 19
import animator from '@ohos.animator';
```
E
esterzhou 已提交
20
## create<sup>9+</sup>
E
ester.zhou 已提交
21

E
esterzhou 已提交
22
create(options: AnimatorOptions): AnimatorResult
E
ester.zhou 已提交
23 24 25 26 27 28

Creates an **Animator** object.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**
E
esterzhou 已提交
29 30 31 32

| Name    | Type                                 | Mandatory  | Description     |
| ------- | ----------------------------------- | ---- | ------- |
| options | [AnimatorOptions](#animatoroptions) | Yes   | Animator options.|
E
ester.zhou 已提交
33 34

**Return value**
E
esterzhou 已提交
35 36 37

| Type                               | Description           |
| --------------------------------- | ------------- |
E
ester.zhou 已提交
38 39 40 41
| [AnimatorResult](#animatorresult) | Animator result.|

**Example**

E
esterzhou 已提交
42
  ```js
E
ester.zhou 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55
import animator, { AnimatorOptions } from '@ohos.animator';

let options: AnimatorOptions = { // The explicit type AnimatorOptions does not need to be emphasized in the xxx.js file.
  duration: 1500,
  easing: "friction",
  delay: 0,
  fill: "forwards",
  direction: "normal",
  iterations: 3,
  begin: 200.0,
  end: 400.0
};
animator.create(options);
E
ester.zhou 已提交
56 57 58 59 60 61
  ```

## AnimatorResult

Defines the animator result.

E
esterzhou 已提交
62
### reset<sup>9+</sup>
E
ester.zhou 已提交
63

E
esterzhou 已提交
64
reset(options: AnimatorOptions): void
E
ester.zhou 已提交
65 66

Updates this animator.
Z
zengyawen 已提交
67

E
ester.zhou 已提交
68
**System capability**: SystemCapability.ArkUI.ArkUI.Full
Z
zengyawen 已提交
69

E
ester.zhou 已提交
70
**Parameters**
E
esterzhou 已提交
71 72 73 74 75 76 77 78 79 80 81

| Name    | Type                                 | Mandatory  | Description     |
| ------- | ----------------------------------- | ---- | ------- |
| options | [AnimatorOptions](#animatoroptions) | Yes   | Animator options.|

**Error codes**

For details about the error codes, see [Animator Error Codes](../errorcodes/errorcode-animator.md).

| ID  | Error Message|
| --------- | ------- |
E
ester.zhou 已提交
82
| 100001    | if no page is found for pageId or fail to get object property list. |
E
esterzhou 已提交
83

Z
zengyawen 已提交
84

E
ester.zhou 已提交
85
**Example**
E
esterzhou 已提交
86 87

```js
E
ester.zhou 已提交
88
let options: AnimatorOptions = { // The explicit type AnimatorOptions does not need to be emphasized in the xxx.js file.
E
esterzhou 已提交
89
  duration: 1500,
E
ester.zhou 已提交
90
  easing: "friction",
E
esterzhou 已提交
91
  delay: 0,
E
ester.zhou 已提交
92 93
  fill: "forwards",
  direction: "normal",
E
esterzhou 已提交
94 95
  iterations: 3,
  begin: 200.0,
E
ester.zhou 已提交
96
  end: 400.0
E
esterzhou 已提交
97 98 99 100 101 102
};
try {
  animator.reset(options);
} catch(error) {
  console.error(`Animator reset failed, error code: ${error.code}, message: ${error.message}.`);
}
Z
zengyawen 已提交
103 104
```

E
ester.zhou 已提交
105
### play
Z
zengyawen 已提交
106

E
ester.zhou 已提交
107
play(): void
Z
zengyawen 已提交
108

E
ester.zhou 已提交
109
Plays 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.
Z
zengyawen 已提交
110

E
ester.zhou 已提交
111
**System capability**: SystemCapability.ArkUI.ArkUI.Full
Z
zengyawen 已提交
112

E
ester.zhou 已提交
113
**Example**
E
esterzhou 已提交
114 115

```js
E
ester.zhou 已提交
116 117
animator.play();
```
Z
zengyawen 已提交
118

E
ester.zhou 已提交
119
### finish
Z
zengyawen 已提交
120

E
ester.zhou 已提交
121
finish(): void
Z
zengyawen 已提交
122

E
ester.zhou 已提交
123
Ends this animation.
Z
zengyawen 已提交
124

E
ester.zhou 已提交
125
**System capability**: SystemCapability.ArkUI.ArkUI.Full
Z
zengyawen 已提交
126

E
ester.zhou 已提交
127
**Example**
E
esterzhou 已提交
128 129

```js
E
ester.zhou 已提交
130 131
animator.finish();
```
Z
zengyawen 已提交
132

E
ester.zhou 已提交
133
### pause
Z
zengyawen 已提交
134

E
ester.zhou 已提交
135
pause(): void
Z
zengyawen 已提交
136

E
ester.zhou 已提交
137
Pauses this animation.
Z
zengyawen 已提交
138

E
ester.zhou 已提交
139
**System capability**: SystemCapability.ArkUI.ArkUI.Full
Z
zengyawen 已提交
140

E
ester.zhou 已提交
141
**Example**
E
esterzhou 已提交
142 143

```js
E
ester.zhou 已提交
144 145
animator.pause();
```
Z
zengyawen 已提交
146

E
ester.zhou 已提交
147
### cancel
Z
zengyawen 已提交
148

E
ester.zhou 已提交
149
cancel(): void
Z
zengyawen 已提交
150

E
ester.zhou 已提交
151
Cancels this animation.
Z
zengyawen 已提交
152

E
ester.zhou 已提交
153
**System capability**: SystemCapability.ArkUI.ArkUI.Full
Z
zengyawen 已提交
154

E
ester.zhou 已提交
155
**Example**
E
esterzhou 已提交
156 157

```js
E
ester.zhou 已提交
158 159 160 161 162 163 164 165 166 167 168 169
animator.cancel();
```

### reverse

reverse(): void

Plays this animation in reverse order.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Example**
E
esterzhou 已提交
170 171

```js
E
ester.zhou 已提交
172 173 174 175 176 177 178 179 180 181 182 183
animator.reverse();
```

### onframe

onframe: (progress: number) => void

Called when a frame is received.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**
E
esterzhou 已提交
184 185 186 187

| Name     | Type    | Mandatory  | Description      |
| -------- | ------ | ---- | -------- |
| progress | number | Yes   | Current progress of the animation.|
E
ester.zhou 已提交
188 189

**Example**
E
esterzhou 已提交
190 191 192 193 194 195

```js
let animatorResult = animator.create(options)
animatorResult.onframe = function(value) {
  console.info("onframe callback")
}
E
ester.zhou 已提交
196 197 198 199 200 201 202 203 204 205 206
```

### onfinish

onfinish: () => void

Called when this animation is finished.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Example**
E
esterzhou 已提交
207 208 209 210 211 212

```js
let animatorResult = animator.create(options)
animatorResult.onfinish = function() {
  console.info("onfinish callback")
}
E
ester.zhou 已提交
213 214 215 216 217 218 219 220 221 222 223
```

### oncancel

oncancel: () => void

Called when this animation is canceled.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Example**
E
esterzhou 已提交
224 225 226 227 228 229

```js
let animatorResult = animator.create(options)
animatorResult.oncancel = function() {
  console.info("oncancel callback")
}
E
ester.zhou 已提交
230 231 232 233 234 235
```

### onrepeat

onrepeat: () => void

E
ester.zhou 已提交
236 237
Called when this animation repeats.

E
ester.zhou 已提交
238 239 240
**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Example**
E
esterzhou 已提交
241 242 243 244 245 246

```js
let animatorResult = animator.create(options)
animatorResult.onrepeat = function() {
  console.info("onrepeat callback")
}
E
ester.zhou 已提交
247
```
E
esterzhou 已提交
248 249


E
ester.zhou 已提交
250 251 252 253 254 255 256

## AnimatorOptions

Defines animator options.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

E
ester.zhou 已提交
257 258 259
| Name      | Type                                                       | Mandatory| Description                                                        |
| ---------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| duration   | number                                                      | Yes  | Duration for playing the animation, in milliseconds.                                  |
E
ester.zhou 已提交
260
| 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>**"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)"**.|
E
ester.zhou 已提交
261 262 263 264 265 266
| delay      | number                                                      | Yes  | Animation delay duration, in milliseconds. Value **0** means that there is no delay.         |
| 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.|
| 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.|
| 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.|
| begin      | number                                                      | Yes  | Start point of the animation interpolation.                                              |
| end        | number                                                      | Yes  | End point of animation interpolation.                                              |
E
esterzhou 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289


## Example
### JavaScript-compatible Web-like Development Paradigm

```html
<!-- hml -->
<div class="container">
  <div class="Animation" style="height: {{divHeight}}px; width: {{divWidth}}px; background-color: red;" onclick="Show">
  </div>
</div>
```

```js
export default {
  data: {
    divWidth: 200,
    divHeight: 200,
    animator: null
  },
  onInit() {
    let options = {
      duration: 1500,
E
ester.zhou 已提交
290
      easing: "friction",
E
esterzhou 已提交
291
      delay: 0,
E
ester.zhou 已提交
292 293
      fill: "forwards",
      direction: "normal",
E
esterzhou 已提交
294 295 296 297 298 299 300 301 302
      iterations: 2,
      begin: 200.0,
      end: 400.0
    };
    this.animator = animator.create(options);
  },
  Show() {
    let options1 = {
      duration: 1500,
E
ester.zhou 已提交
303
      easing: "friction",
E
esterzhou 已提交
304
      delay: 0,
E
ester.zhou 已提交
305
      fill: "forwards",
E
esterzhou 已提交
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
      direction: "normal",
      iterations: 2,
      begin: 0,
      end: 400.0,
    };
    try {
      this.animator.reset(options1);
    } catch(error) {
      console.error(`Animator reset failed, error code: ${error.code}, message: ${error.message}.`);
    }
    let _this = this;
    this.animator.onframe = function(value) {
      _this.divWidth = value;
      _this.divHeight = value;
    };
    this.animator.play();
  }
}
```

  ![en-us_image_00007](figures/en-us_image_00007.gif)

### ArkTS-based Declarative Development Paradigm

```ts
import animator from '@ohos.animator';

@Entry
@Component
struct AnimatorTest {
  private TAG: string = '[AnimatorTest]'
  private backAnimator: any = undefined
  private flag: boolean = false
  @State wid: number = 100
  @State hei: number = 100

  create() {
    let _this = this
    this.backAnimator = animator.create({
      duration: 2000,
E
ester.zhou 已提交
346
      easing: "ease",
E
esterzhou 已提交
347
      delay: 0,
E
ester.zhou 已提交
348 349
      fill: "none",
      direction: "normal",
E
esterzhou 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
      iterations: 1,
      begin: 100,
      end: 200
    })
    this.backAnimator.onfinish = function () {
      _this.flag = true
      console.info(_this.TAG, 'backAnimator onfinish')
    }
    this.backAnimator.onrepeat = function () {
      console.info(_this.TAG, 'backAnimator repeat')
    }
    this.backAnimator.oncancel = function () {
      console.info(_this.TAG, 'backAnimator cancel')
    }
    this.backAnimator.onframe = function (value) {
      _this.wid = value
      _this.hei = value
    }
  }

  build() {
    Column() {
      Column() {
        Column()
          .width(this.wid)
          .height(this.hei)
          .backgroundColor(Color.Red)
      }
      .width('100%')
      .height(300)

      Column() {
        Row() {
          Button('create')
            .fontSize(30)
            .fontColor(Color.Black)
            .onClick(() => {
              this.create()
            })
        }
        .padding(10)

        Row() {
          Button('play')
            .fontSize(30)
            .fontColor(Color.Black)
            .onClick(() => {
              this.flag = false
              this.backAnimator.play()
            })
        }
        .padding(10)

        Row() {
          Button('pause')
            .fontSize(30)
            .fontColor(Color.Black)
            .onClick(() => {
              this.backAnimator.pause()
            })
        }
        .padding(10)

        Row() {
          Button('finish')
            .fontSize(30)
            .fontColor(Color.Black)
            .onClick(() => {
              this.flag = true
              this.backAnimator.finish()
            })
        }
        .padding(10)

        Row() {
          Button('reverse')
            .fontSize(30)
            .fontColor(Color.Black)
            .onClick(() => {
              this.flag = false
              this.backAnimator.reverse()
            })
        }
        .padding(10)

        Row() {
          Button('cancel')
            .fontSize(30)
            .fontColor(Color.Black)
            .onClick(() => {
              this.backAnimator.cancel()
            })
        }
        .padding(10)

        Row() {
          Button('reset')
            .fontSize(30)
            .fontColor(Color.Black)
            .onClick(() => {
              if (this.flag) {
                this.flag = false
                this.backAnimator.reset({
                  duration: 5000,
E
ester.zhou 已提交
454
                  easing: "ease-in",
E
esterzhou 已提交
455
                  delay: 0,
E
ester.zhou 已提交
456 457
                  fill: "none",
                  direction: "normal",
E
esterzhou 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
                  iterations: 4,
                  begin: 100,
                  end: 300
                })
              } else {
                console.info(this.TAG, 'Animation not ended')
              }
            })
        }
        .padding(10)
      }
    }
  }
}
```

## update<sup>(deprecated)</sup>

update(options: AnimatorOptions): void

Updates this animator.

This API is deprecated since API version 9. You are advised to use [reset<sup>9+</sup>](#reset9) instead.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name    | Type                                 | Mandatory  | Description     |
| ------- | ----------------------------------- | ---- | ------- |
| options | [AnimatorOptions](#animatoroptions) | Yes   | Animator options.|

**Example**

```js
animator.update(options);
```

## createAnimator<sup>(deprecated)</sup>

createAnimator(options: AnimatorOptions): AnimatorResult

Creates an **Animator** object.

This API is deprecated since API version 9. You are advised to use [create<sup>9+</sup>](#create9) instead.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name    | Type                                 | Mandatory  | Description     |
| ------- | ----------------------------------- | ---- | ------- |
| options | [AnimatorOptions](#animatoroptions) | Yes   | Animator options.|

**Return value**

| Type                               | Description           |
| --------------------------------- | ------------- |
| [AnimatorResult](#animatorresult) | Animator result.|

**Example**

```js
E
ester.zhou 已提交
521
let options: AnimatorOptions = { // The explicit type AnimatorOptions does not need to be emphasized in the xxx.js file.
E
esterzhou 已提交
522
  duration: 1500,
E
ester.zhou 已提交
523
  easing: "friction",
E
esterzhou 已提交
524
  delay: 0,
E
ester.zhou 已提交
525 526
  fill: "forwards",
  direction: "normal",
E
esterzhou 已提交
527 528 529 530 531 532
  iterations: 3,
  begin: 200.0,
  end: 400.0,
};
this.animator = animator.createAnimator(options);
```