• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Lottie
2
3**Lottie** allows you to implement animation-specific operations.
4
5> **NOTE**
6>
7> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10
11## Modules to Import
12
13```
14import lottie from '@ohos/lottieETS'
15```
16
17> **NOTE**
18>
19> In the **Terminal** window, run the `npm install @ohos/lottieETS` command to download Lottie. The download requires the related permission.
20>
21> To install an OpenHarmony npm third-party package, run the `npm config set @ohos:registry=https://repo.harmonyos.com/npm/` command to set the repository address.
22
23
24## lottie.loadAnimation
25
26loadAnimation(
27
28path: string, container: object, render: string, loop: boolean, autoplay: boolean, name: string ): AnimationItem
29
30Loads an animation. Before calling this API, declare the **Animator('__lottie_ets')** object and make sure the canvas layout is complete. This API can be used together with the lifecycle callback **onReady()** of the **Canvas** component.
31
32**Parameters**
33
34| Name          | Type                       | Mandatory| Description                                                        |
35| -------------- | --------------------------- | ---- | ------------------------------------------------------------ |
36| path           | string                      | Yes  | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**|
37| container      | object                      | Yes  | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.|
38| render         | string                      | Yes  | Rendering type. The value can only be **"canvas"**.                                  |
39| loop           | boolean \| number | No  | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.|
40| autoplay       | boolean                     | No   | Whether to automatically play the animation.<br>Default value: **true**                          |
41| name           | string                      | No   | Custom animation name. In later versions, the name can be used to reference and control the animation.<br/>Default value: null |
42| initialSegment | [number, number]            | No   | Start frame and end frame of the animation, respectively.            |
43
44
45## lottie.destroy
46
47destroy(name: string): void
48
49Destroys the animation. This API must be called when a page exits. This API can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**.
50
51**Parameters**
52
53| Name  | Type    | Mandatory  | Description                                      |
54| ---- | ------ | ---- | ---------------------------------------- |
55| name | string | Yes   | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** API. By default, all animations are destroyed. |
56
57**Example**
58
59  ```ts
60  // xxx.ets
61  import lottie from '@ohos/lottieETS'
62
63  @Entry
64  @Component
65  struct Index {
66    private controller: CanvasRenderingContext2D = new CanvasRenderingContext2D()
67    private animateName: string = "animate"
68    private animatePath: string = "common/lottie/data.json"
69    private animateItem: any = null
70
71    onPageHide(): void {
72      console.log('onPageHide')
73      lottie.destroy()
74    }
75
76    build() {
77      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
78        Canvas(this.controller)
79        .width('30%')
80        .height('20%')
81        .backgroundColor('#0D9FFB')
82        .onReady(() => {
83          console.log('canvas onAppear');
84          this.animateItem = lottie.loadAnimation({
85            container: this.controller,
86            renderer: 'canvas',
87            loop: true,
88            autoplay: true,
89            name: this.animateName,
90            path: this.animatePath,
91          })
92        })
93
94        Animator('__lottie_ets') // declare Animator('__lottie_ets') when use lottie
95        Button('load animation')
96          .onClick(() => {
97          if (this.animateItem != null) {
98            this.animateItem.destroy()
99            this.animateItem = null
100          }
101          this.animateItem = lottie.loadAnimation({
102            container: this.controller,
103            renderer: 'canvas',
104            loop: true,
105            autoplay: true,
106            name: this.animateName,
107            path: this.animatePath,
108            initialSegment: [10, 50],
109          })
110        })
111
112        Button('destroy animation')
113          .onClick(() => {
114            lottie.destroy(this.animateName)
115            this.animateItem = null
116          })
117      }
118      .width('100%')
119      .height('100%')
120    }
121  }
122  ```
123
124  ![en-us_image_0000001194352468](figures/en-us_image_0000001194352468.gif)
125
126
127## lottie.play
128
129play(name: string): void
130
131Plays a specified animation.
132
133**Parameters**
134
135| Name  | Type    | Mandatory  | Description                                      |
136| ---- | ------ | ---- | ---------------------------------------- |
137| name | string | Yes   | Name of the animation to play, which is the same as the **name** in the **loadAnimation** API. By default, all animations are played. |
138
139**Example**
140
141  ```ts
142  lottie.play(this.animateName)
143  ```
144
145
146## lottie.pause
147
148pause(name: string): void
149
150Pauses a specified animation. The next time **lottie.play()** is called, the animation starts from the current frame.
151
152**Parameters**
153
154| Name  | Type    | Mandatory  | Description                                      |
155| ---- | ------ | ---- | ---------------------------------------- |
156| name | string | Yes   | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** API. By default, all animations are paused. |
157
158**Example**
159
160  ```ts
161  lottie.pause(this.animateName)
162  ```
163
164
165## lottie.togglePause
166
167togglePause(name: string): void
168
169Pauses or plays a specified animation. This API is equivalent to the switching between **lottie.play()** and **lottie.pause()**.
170
171**Parameters**
172
173| Name  | Type    | Mandatory  | Description                                      |
174| ---- | ------ | ---- | ---------------------------------------- |
175| name | string | Yes   | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are paused or played. |
176
177**Example**
178
179  ```ts
180  lottie.togglePause(this.animateName)
181  ```
182
183
184## lottie.stop
185
186stop(name: string): void
187
188Stops the specified animation. The next time **lottie.play()** is called, the animation starts from the first frame.
189
190**Parameters**
191
192| Name  | Type    | Mandatory  | Description                                      |
193| ---- | ------ | ---- | ---------------------------------------- |
194| name | string | Yes   | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are stopped. |
195
196**Example**
197
198  ```ts
199  lottie.stop(this.animateName)
200  ```
201
202
203## lottie.setSpeed
204
205setSpeed(speed: number, name: string): void
206
207Sets the playback speed of the specified animation.
208
209**Parameters**
210
211| Name   | Type    | Mandatory  | Description                                      |
212| ----- | ------ | ---- | ---------------------------------------- |
213| speed | number | Yes   | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is **0**, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. |
214| name  | string | Yes   | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are set. |
215
216**Example**
217
218  ```ts
219  lottie.setSpeed(5, this.animateName)
220  ```
221
222
223## lottie.setDirection
224
225setDirection(direction: AnimationDirection, name: string): void
226
227Sets the direction in which the specified animation plays.
228
229**Parameters**
230
231| Name       | Type                | Mandatory  | Description                                      |
232| --------- | ------------------ | ---- | ---------------------------------------- |
233| direction | AnimationDirection | Yes   | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br>AnimationDirection: 1 \| -1 |
234| name      | string             | Yes   | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are set. |
235
236**Example**
237
238  ```ts
239  lottie.setDirection(-1, this.animateName)
240  ```
241
242
243## AnimationItem
244
245Defines an **AnimationItem** object, which is returned by the **loadAnimation** API and has attributes and APIs. The attributes are described as follows:
246
247| Name             | Type                                    | Description                                    |
248| ----------------- | ---------------------------------------- | ---------------------------------------- |
249| name              | string                                   | Animation name.                                   |
250| isLoaded          | boolean                                  | Whether the animation is loaded.                                |
251| currentFrame      | number                                   | Frame that is being played. The default precision is a floating-point number greater than or equal to 0.0. After **setSubframe(false)** is called, the value is a positive integer without decimal points.|
252| currentRawFrame   | number                                   | Number of frames that are being played. The precision is a floating point number greater than or equal to 0.0.           |
253| firstFrame        | number                                   | First frame of the animation segment that is being played.                           |
254| totalFrames       | number                                   | Total number of frames in the animation segment that is being played.                             |
255| frameRate         | number                                   | Frame rate (frame/s).                      |
256| frameMult         | number                                   | Frame rate (frame/ms).                     |
257| playSpeed         | number                                   | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is **0**, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. |
258| playDirection     | number                                   | Playback direction.<br>**1**: forward.<br/>**-1**: backward. |
259| playCount         | number                                   | Number of times the animation plays.                              |
260| isPaused          | boolean                                  | Whether the current animation is paused. The value **true** means that the animation is paused.            |
261| autoplay          | boolean                                  | Whether to automatically play the animation upon completion of the loading. The value **false** means that the **play()** API needs to be called to start playing. |
262| loop              | boolean \| number                        | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. |
263| renderer          | any                                      | Animation rendering object, which depends on the rendering type.                  |
264| animationID       | string                                   | Animation ID.                                   |
265| timeCompleted     | number                                   | Number of frames that are played for an animation sequence. The value is affected by the setting of **AnimationSegment** and is the same as the value of **totalFrames**.|
266| segmentPos        | number                                   | ID of the current animation segment. The value is a positive integer greater than or equal to 0.            |
267| isSubframeEnabled | boolean                                  | Whether the precision of **currentFrame** is a floating point number.               |
268| segments          | AnimationSegment \| AnimationSegment[]   | Current segment of the animation.                              |
269
270
271## AnimationItem.play
272
273play(name?: string): void
274
275Plays an animation.
276
277**Parameters**
278
279| Name  | Type    | Mandatory  | Description             |
280| ---- | ------ | ---- | --------------- |
281| name | string | No   | Name of the target animation. By default, the value is null.|
282
283**Example**
284
285  ```ts
286  this.animateItem.play()
287  ```
288
289
290## AnimationItem.destroy
291
292destroy(name?: string): void
293
294Destroys an animation.
295
296**Parameters**
297
298| Name  | Type    | Mandatory  | Description             |
299| ---- | ------ | ---- | --------------- |
300| name | string | No   | Name of the target animation. By default, the value is null.|
301
302**Example**
303
304  ```ts
305  this.animateItem.destroy()
306  ```
307
308
309## AnimationItem.pause
310
311pause(name?: string): void
312
313Pauses an animation. When the **play** API is called next time, the animation is played from the current frame.
314
315**Parameters**
316
317| Name  | Type    | Mandatory  | Description             |
318| ---- | ------ | ---- | --------------- |
319| name | string | No   | Name of the target animation. By default, the value is null.|
320
321**Example**
322
323  ```ts
324  this.animateItem.pause()
325  ```
326
327
328## AnimationItem.togglePause
329
330togglePause(name?: string): void
331
332Pauses or plays an animation. This API is equivalent to the switching between **play** and **pause**.
333
334**Parameters**
335
336| Name  | Type    | Mandatory  | Description             |
337| ---- | ------ | ---- | --------------- |
338| name | string | No   | Name of the target animation. By default, the value is null.|
339
340**Example**
341
342  ```ts
343  this.animateItem.togglePause()
344  ```
345
346
347## AnimationItem.stop
348
349stop(name?: string): void
350
351Stops an animation. When the **play** API is called next time, the animation is played from the first frame.
352
353**Parameters**
354
355| Name  | Type    | Mandatory  | Description             |
356| ---- | ------ | ---- | --------------- |
357| name | string | No   | Name of the target animation. By default, the value is null.|
358
359**Example**
360
361  ```ts
362  this.animateItem.stop()
363  ```
364
365
366## AnimationItem.setSpeed
367
368setSpeed(speed: number): void
369
370Sets the playback speed of an animation.
371
372**Parameters**
373
374| Name   | Type    | Mandatory  | Description                                      |
375| ----- | ------ | ---- | ---------------------------------------- |
376| speed | number | Yes   | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is **0**, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. |
377
378**Example**
379
380  ```ts
381  this.animateItem.setSpeed(5);
382  ```
383
384
385## AnimationItem.setDirection
386
387setDirection(direction: AnimationDirection): void
388
389Sets the playback direction of an animation.
390
391**Parameters**
392
393| Name       | Type                | Mandatory  | Description                                      |
394| --------- | ------------------ | ---- | ---------------------------------------- |
395| direction | AnimationDirection | Yes   | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br>AnimationDirection: 1 \| -1.|
396
397**Example**
398
399  ```ts
400  this.animateItem.setDirection(-1)
401  ```
402
403
404## AnimationItem.goToAndStop
405
406goToAndStop(value: number, isFrame?: boolean): void
407
408Sets the animation to stop at the specified frame or time.
409
410**Parameters**
411
412| Name     | Type     | Mandatory  | Description                                      |
413| ------- | ------- | ---- | ---------------------------------------- |
414| value   | number  | Yes   | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop.                    |
415| isFrame | boolean | No    | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress.<br/>Default value: **false** |
416| name    | string  | No    | Name of the target animation. By default, the value is null.                         |
417
418**Example**
419
420  ```ts
421  // Set the animation to stop at the specified frame.
422  this.animateItem.goToAndStop(25, true)
423  // Set the animation to stop at the specified time progress.
424  this.animateItem.goToAndStop(300, false, this.animateName)
425  ```
426
427
428## AnimationItem.goToAndPlay
429
430goToAndPlay(value: number, isFrame: boolean, name?: string): void
431
432Sets the animation to start from the specified frame or time progress.
433
434**Parameters**
435
436| Name     | Type     | Mandatory  | Description                                      |
437| ------- | ------- | ---- | ---------------------------------------- |
438| value   | number  | Yes   | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start.                     |
439| isFrame | boolean | Yes   | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress.<br/>Default value: **false** |
440| name    | string  | No    | Name of the target animation.<br/>Default value: null      |
441
442**Example**
443
444  ```ts
445  // Set the animation to stop at the specified frame.
446  this.animateItem.goToAndPlay(25, true)
447  // Set the animation to stop at the specified time progress.
448  this.animateItem.goToAndPlay(300, false, this.animateName)
449  ```
450
451
452## AnimationItem.playSegments
453
454playSegments(segments: AnimationSegment | AnimationSegment[], forceFlag: boolean): void
455
456Sets the animation to play only the specified segment.
457
458**Parameters**
459
460| Name       | Type                                      | Mandatory  | Description                                      |
461| --------- | ---------------------------------------- | ---- | ---------------------------------------- |
462| segments  | AnimationSegment = [number, number] \| AnimationSegment[] | Yes   | Segment or segment list.<br>If all segments in the segment list are played, only the last segment is played in the next cycle.|
463| forceFlag | boolean                                                   | Yes   | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed.          |
464
465**Example**
466
467  ```ts
468  // Set the animation to play the specified segment.
469  this.animateItem.playSegments([10, 20], false)
470  // Set the animation to play the specified segment list.
471  this.animateItem.playSegments([[0, 5], [20, 30]], true)
472  ```
473
474
475## AnimationItem.resetSegments
476
477resetSegments(forceFlag: boolean): void
478
479Resets the settings configured by the **playSegments** API to play all the frames.
480
481**Parameters**
482
483| Name       | Type     | Mandatory  | Description                            |
484| --------- | ------- | ---- | ------------------------------ |
485| forceFlag | boolean | Yes   | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed.|
486
487**Example**
488
489  ```ts
490  this.animateItem.resetSegments(true)
491  ```
492
493
494## AnimationItem.resize
495
496resize(): void
497
498Resizes the animation layout.
499
500**Example**
501
502  ```ts
503  this.animateItem.resize()
504  ```
505
506
507## AnimationItem.setSubframe
508
509setSubframe(useSubFrame: boolean): void
510
511Sets the precision of the **currentFrame** attribute to display floating-point numbers.
512
513**Parameters**
514
515| Name          | Type     | Mandatory  | Description                                      |
516| ------------ | ------- | ---- | ---------------------------------------- |
517| useSubFrames | boolean | Yes   | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.<br>**true**: The **currentFrame** attribute displays floating-point numbers.<br>**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers.|
518
519**Example**
520
521  ```ts
522  this.animateItem.setSubframe(false)
523  ```
524
525
526## AnimationItem.getDuration
527
528getDuration(inFrames?: boolean): void
529
530Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** API.
531
532**Parameters**
533
534| Name      | Type     | Mandatory  | Description                                      |
535| -------- | ------- | ---- | ---------------------------------------- |
536| inFrames | boolean | No   | Whether to obtain the duration or number of frames.<br>**true**: number of frames.<br>**false**: duration, in ms.<br/>Default value: **false** |
537
538**Example**
539
540  ```ts
541  this.animateItem.getDuration(true)
542  ```
543
544
545## AnimationItem.addEventListener
546
547addEventListener&lt;T = any&gt;(name: AnimationEventName, callback: AnimationEventCallback&lt;T&gt;): () =&gt; void
548
549Adds an event listener. After the event is complete, the specified callback is triggered. This API returns the function object that can delete the event listener.
550
551**Parameters**
552
553| Name      | Type                             | Mandatory  | Description                                      |
554| -------- | ------------------------------- | ---- | ---------------------------------------- |
555| name     | AnimationEventName              | Yes   | Animation event type. The available options are as follows:<br>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'|
556| callback | AnimationEventCallback&lt;T&gt; | Yes   | Custom callback.                               |
557
558**Example**
559
560  ```ts
561  private callbackItem: any = function() {
562      console.log("grunt loopComplete")
563  }
564  let delFunction = this.animateItem.addEventListener('loopComplete', this.animateName)
565
566  // Delete the event listener.
567  delFunction()
568  ```
569
570
571## AnimationItem.removeEventListener
572
573removeEventListener&lt;T = any&gt;(name: AnimationEventName, callback?: AnimationEventCallback&lt;T&gt;): void
574
575Removes an event listener.
576
577**Parameters**
578
579| Name      | Type                             | Mandatory  | Description                                      |
580| -------- | ------------------------------- | ---- | ---------------------------------------- |
581| name     | AnimationEventName              | Yes   | Animation event type. The available options are as follows:<br>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'|
582| callback | AnimationEventCallback&lt;T&gt; | No    | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed.           |
583
584**Example**
585
586  ```ts
587  this.animateItem.removeEventListener('loopComplete', this.animateName)
588  ```
589
590
591## AnimationItem.triggerEvent
592
593triggerEvent&lt;T = any&gt;(name: AnimationEventName, args: T): void
594
595Directly triggers all configured callbacks of a specified event.
596
597**Parameters**
598
599| Name  | Type                | Mandatory  | Description       |
600| ---- | ------------------ | ---- | --------- |
601| name | AnimationEventName | Yes   | Animation event type. |
602| args | any                | Yes   | Custom callback parameters.|
603
604**Example**
605
606  ```ts
607  private triggerCallBack: any = function(item) {
608      console.log("trigger loopComplete, name:" + item.name)
609  }
610
611  this.animateItem.addEventListener('loopComplete', this.triggerCallBack)
612  this.animateItem.triggerEvent('loopComplete', this.animateItem)
613  this.animateItem.removeEventListener('loopComplete', this.triggerCallBack)
614  ```
615