js-apis-animator.md 15.7 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 9
>
> This module can be used only after a component instance is created, and it cannot be used in the [UIAbility](./js-apis-app-ability-uiAbility.md).
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 43 44
  ```js
  let options = {
    duration: 1500,
E
ester.zhou 已提交
45
    easing: "friction",
E
esterzhou 已提交
46
    delay: 0,
E
ester.zhou 已提交
47 48
    fill: "forwards",
    direction: "normal",
E
esterzhou 已提交
49 50
    iterations: 3,
    begin: 200.0,
E
ester.zhou 已提交
51
    end: 400.0
E
esterzhou 已提交
52 53
  };
  animator.create(options);
E
ester.zhou 已提交
54 55 56 57 58 59
  ```

## AnimatorResult

Defines the animator result.

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

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

Updates this animator.
Z
zengyawen 已提交
65

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

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

| 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 已提交
80
| 100001    | if no page is found for pageId or fail to get object property list. |
E
esterzhou 已提交
81

Z
zengyawen 已提交
82

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

```js
let options = {
  duration: 1500,
E
ester.zhou 已提交
88
  easing: "friction",
E
esterzhou 已提交
89
  delay: 0,
E
ester.zhou 已提交
90 91
  fill: "forwards",
  direction: "normal",
E
esterzhou 已提交
92 93
  iterations: 3,
  begin: 200.0,
E
ester.zhou 已提交
94
  end: 400.0
E
esterzhou 已提交
95 96 97 98 99 100
};
try {
  animator.reset(options);
} catch(error) {
  console.error(`Animator reset failed, error code: ${error.code}, message: ${error.message}.`);
}
Z
zengyawen 已提交
101 102
```

E
ester.zhou 已提交
103
### play
Z
zengyawen 已提交
104

E
ester.zhou 已提交
105
play(): void
Z
zengyawen 已提交
106

E
ester.zhou 已提交
107
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 已提交
108

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

E
ester.zhou 已提交
111
**Example**
E
esterzhou 已提交
112 113

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

E
ester.zhou 已提交
117
### finish
Z
zengyawen 已提交
118

E
ester.zhou 已提交
119
finish(): void
Z
zengyawen 已提交
120

E
ester.zhou 已提交
121
Ends this animation.
Z
zengyawen 已提交
122

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

E
ester.zhou 已提交
125
**Example**
E
esterzhou 已提交
126 127

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

E
ester.zhou 已提交
131
### pause
Z
zengyawen 已提交
132

E
ester.zhou 已提交
133
pause(): void
Z
zengyawen 已提交
134

E
ester.zhou 已提交
135
Pauses this animation.
Z
zengyawen 已提交
136

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

E
ester.zhou 已提交
139
**Example**
E
esterzhou 已提交
140 141

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

E
ester.zhou 已提交
145
### cancel
Z
zengyawen 已提交
146

E
ester.zhou 已提交
147
cancel(): void
Z
zengyawen 已提交
148

E
ester.zhou 已提交
149
Cancels this animation.
Z
zengyawen 已提交
150

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

E
ester.zhou 已提交
153
**Example**
E
esterzhou 已提交
154 155

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

### reverse

reverse(): void

Plays this animation in reverse order.

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

**Example**
E
esterzhou 已提交
168 169

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

### onframe

onframe: (progress: number) => void

Called when a frame is received.

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

**Parameters**
E
esterzhou 已提交
182 183 184 185

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

**Example**
E
esterzhou 已提交
188 189 190 191 192 193

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

### onfinish

onfinish: () => void

Called when this animation is finished.

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

**Example**
E
esterzhou 已提交
205 206 207 208 209 210

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

### oncancel

oncancel: () => void

Called when this animation is canceled.

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

**Example**
E
esterzhou 已提交
222 223 224 225 226 227

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

### onrepeat

onrepeat: () => void

E
ester.zhou 已提交
234 235
Called when this animation repeats.

E
ester.zhou 已提交
236 237 238
**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Example**
E
esterzhou 已提交
239 240 241 242 243 244

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


E
ester.zhou 已提交
248 249 250 251 252 253 254

## AnimatorOptions

Defines animator options.

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

E
ester.zhou 已提交
255 256 257 258 259 260 261 262 263 264
| Name      | Type                                                       | Mandatory| Description                                                        |
| ---------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| duration   | number                                                      | Yes  | Duration for playing the animation, in milliseconds.                                  |
| 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 the input parameters must range from 0 to 1.<br>**steps(number, step-position)**: The animation uses a step curve. The **number** must be set and only an integer is supported. **step-position** is optional. It can be set to **start** or **end**. The default value is **end**.|
| 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 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287


## 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 已提交
288
      easing: "friction",
E
esterzhou 已提交
289
      delay: 0,
E
ester.zhou 已提交
290 291
      fill: "forwards",
      direction: "normal",
E
esterzhou 已提交
292 293 294 295 296 297 298 299 300
      iterations: 2,
      begin: 200.0,
      end: 400.0
    };
    this.animator = animator.create(options);
  },
  Show() {
    let options1 = {
      duration: 1500,
E
ester.zhou 已提交
301
      easing: "friction",
E
esterzhou 已提交
302
      delay: 0,
E
ester.zhou 已提交
303
      fill: "forwards",
E
esterzhou 已提交
304 305 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
      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 已提交
344
      easing: "ease",
E
esterzhou 已提交
345
      delay: 0,
E
ester.zhou 已提交
346 347
      fill: "none",
      direction: "normal",
E
esterzhou 已提交
348 349 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
      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 已提交
452
                  easing: "ease-in",
E
esterzhou 已提交
453
                  delay: 0,
E
ester.zhou 已提交
454 455
                  fill: "none",
                  direction: "normal",
E
esterzhou 已提交
456 457 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
let options = {
  duration: 1500,
E
ester.zhou 已提交
521
  easing: "friction",
E
esterzhou 已提交
522
  delay: 0,
E
ester.zhou 已提交
523 524
  fill: "forwards",
  direction: "normal",
E
esterzhou 已提交
525 526 527 528 529 530
  iterations: 3,
  begin: 200.0,
  end: 400.0,
};
this.animator = animator.createAnimator(options);
```