# lottieArkTS_TaskPool **Repository Path**: summor/lottieArkTS_TaskPool ## Basic Information - **Project Name**: lottieArkTS_TaskPool - **Description**: lottieArkTS - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 5 - **Created**: 2024-09-13 - **Last Updated**: 2024-09-13 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # lottie ## Introduction An animation library for OpenHarmony, lottie parses Adobe After Effects animations exported as JSON with Bodymovin and renders them natively on mobile. ![showlottie](./screenshot/showlottie-EN.gif) ## Download and Installation ``` ohpm install @ohos/lottie ``` For details, see [Installing an OpenHarmony HAR](https://gitee.com/openharmony-tpc/docs/blob/master/OpenHarmony_har_usage.md). ## How to Use To start off, get required data prepared. lottie animations are created in Adobe After Effects and exported with Bodymovin as JSON. In creating an animation in Adobe After Effects, you need to set the animation attributes, including the width (**w**), height (**h**), Bodymovin version (**v**), frame rate (**fr**), start frame (**ip**), end frame (**op**), static resource information (**assets**), and layer information (**layers**). For demo test purposes, you can use the [JSON files in the example](https://gitee.com/openharmony-tpc/lottie/tree/master/entry/src/main/ets/common/lottie). 1. Import the component to the corresponding class. ``` import lottie from '@ohos/lottie' ``` 2. Build a rendering context. ``` private mainRenderingSettings: RenderingContextSettings = new RenderingContextSettings(true) private mainCanvasRenderingContext: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.mainRenderingSettings) ``` 3. Place the JSON file required by the animation in the directory at the same level as **pages** and reference the file. (In this example, the JSON file used is **entry/src/main/ets/common/lottie/data.json**.) Note: The JSON file path cannot be a relative path, such as one that starts with a single dot (.) or double dot (..), followed by a slash (/). Using a relative path will result in a failure to fetch the animation source. This is because a relative path referenced in the index page is based on the **index.ets** file, while the path passed to the **loadAnimation** API is based on the **pages** folder. Therefore, for example, if a JSON file **data.json** is stored in the **pages** folder, the path should be **pages/common/data.json**. ``` private path:string = "common/lottie/data.json" Or private jsonData:string = {"v":"4.6.6","fr":24,"ip":0,"op":72,"w":1000,"h":1000,"nm":"Comp 2","ddd":0,"assets":[],...} ``` 4. Configure the bound canvas. ``` Canvas(this.mainCanvasRenderingContext) .width('50%') .height(360 + 'px') .backgroundColor(Color.Gray) .onReady(()=>{ // Anti-aliasing settings this.mainCanvasRenderingContext.imageSmoothingEnabled = true; this.mainCanvasRenderingContext.imageSmoothingQuality = 'medium' }) ``` - Note: It is recommended that the aspect ratio set for the canvas be the same as that of the JSON animation resource. - The anti-aliasing settings in this example: **mainCanvasRenderingContext.imageSmoothingEnabled = true** and **mainCanvasRenderingContext.imageSmoothingQuality = 'medium'** - A canvas is cleared before an animation is drawn on it. - 5. Load the animation. - Pay attention to the time when you want your animation to load. If you want the animation to load upon a button click, simply place the animation loading logic in the click event. If you want the animation to load automatically once the page where it is located is displayed, you must place the animation loading logic within or after the **onReady()** lifecycle callback. - For a canvas to load one animation multiple times or load different animations, manually destroy the previously loaded animation (**lottie.destroy()** or **animationItem.destroy()**) each time before the canvas loads again. ``` this.animationItem? .destroy('2016'); // Destroy the previously loaded animation before loading a new one. this.animationItem = lottie.loadAnimation({ container: this.mainCanvasRenderingContext, // Rendering context renderer: 'canvas', // Rendering mode loop: true, // Whether the animation is repeated. The default value is true. autoplay: true, // Whether to enable automatic playback. The default value is true. name: '2016', // Animation name contentMode: 'Contain', // Fill mode path: this.path, // JSON file path initialSegment: [10,50] // Initial segment of the animation }) Or lottie.loadAnimation({ container: this.mainCanvasRenderingContext, // Rendering context renderer: 'canvas', // Rendering mode loop: true, // Whether the animation is repeated. The default value is true. autoplay: true, // Whether to enable automatic playback. The default value is true. contentMode: 'Contain', // Fill mode animationData: this.jsonData, // JSON object data initialSegment: [10,50] // Initial segment of the animation }) ``` - To load an animation, use either **path** or **animationData**. - **path**: Only relative paths under **entry/src/main/ets** are allowed. Cross-package file search is not supported. - **animationData**: Set this parameter based on **ResourceManager**. - Load external resource images: By default, the application reads images in the sandbox path. If the specified image is not found in the sandbox, the application searches for it in **rawfile**. 6. Load an animation with an HSP. - To load an animation with an HSP, pass in the **context** parameter to the **loadAnimation** API. This parameter is optional and not required where no HSP is involved. ``` let contexts = getContext(this).createModuleContext('library') as common.UIAbilityContext; lottie.loadAnimation({ container: this.mainCanvasRenderingContext, // Rendering context renderer: 'canvas', // Rendering mode loop: true, // Whether the animation is repeated. The default value is true. autoplay: true, // Whether to enable automatic playback. The default value is true. animationData: this.jsonData, // JSON object data context: contexts, // Current context contentMode: 'Contain', // Fill mode initialSegment: [10,50] // Initial segment of the animation }) ``` - When an HSP is involved, lottie loads the JSON resource file through **animationData**. As such, you must place the JSON resource file in **rawfile**. - To load an animation, use **animationData**. - **animationData**: Set this parameter based on **ResourceManager**. ``` let resStr = new util.TextDecoder('utf-8',{ignoreBOM: true}); let context = getContext(this).createModuleContext('library') as common.UIAbilityContext context.resourceManager.getRawFile('grunt.json',(err: Error,data: Uint8Array) =>{ if(data === null || data === undefined || data.buffer=== undefined){ return; } let lottieStr = resStr.decode(new Uint8Array(data.buffer)); this.jsonData = JSON.parse(lottieStr); }) ``` 7. Control animation playback. - Play the animation. ``` lottie.play() // Play all animations. Or animationItem.play() // Play a given animation. ``` - Stop the animation. ``` lottie.stop() // Stop all animations. Or animationItem.stop() // Stop a given animation. ``` - Pause the animation. ``` lottie.pause() // Pause all animations. Or animationItem.pause() // Pause a given animation. ``` - Switch the animation playback state between running and paused. ``` lottie.togglePause() // Switch the playback state between running and paused for all animations. Or animationItem.togglePause() // Switch the playback state between running and paused for a given animation. ``` - Set the playback speed. > Note: If the value is greater than **0**, the animation plays forwards. If the value is less than **0**, the animation plays backwards. 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. ``` lottie.setSpeed(1) // Set the playback speed for all animations. Or animationItem.setSpeed(1) // Set the playback speed for a given animation. ``` - Set the playback direction. > Note: The value **1** indicates forward, and **-1** indicates backward. ``` lottie.setDirection(1) // Set the playback direction for all animations. Or animationItem.setDirection(1) // Set the playback direction for a given animation. ``` - Destroy the animation. > Note: An animation needs to be destroyed when the page where it is located disappears or exits. The **destroy()** API can be used together with the **aboutToDisappear()** and **onPageHide()** callbacks of the page or the **onDisAppear()** callback of the canvas component. ``` lottie.destroy() // Destroy all animations. Or animationItem.destroy() // Destroy a given animation. ``` - Stop the animation at a frame or a point of time. > Note: The second parameter specifies whether to control by frame or time (in milliseconds). The value **true** indicates that the control is performed by frame, and the value **false** (default) indicates that the control is performed by time. ``` animationItem.goToAndStop(250,true) Or animationItem.goToAndStop(5000,false) ``` - Start the animation from a frame or a point of time. > Note: The second parameter specifies whether to control by frame or time (in milliseconds). The value **true** indicates that the control is performed by frame, and the value **false** (default) indicates that the control is performed by time. ``` animationItem.goToAndPlay(250,true) Or animationItem.goToAndPlay(12000,false) ``` - Set an animation segment to limit the frame range for animation playback. ``` animationItem.setSegment(5,15); ``` - Play animation segments. > Note: The second parameter specifies whether the setting takes effect immediately. The value **true** indicates the setting takes effect immediately, and **false** indicates that the setting takes effect upon the next playback. ``` animationItem.playSegments([5,15],[20,30],true) ``` - Reset animation segments so that the animation plays from the start frame. > Note: The value **true** indicates the setting takes effect immediately, and **false** indicates that the setting takes effect upon the next playback. ``` animationItem.resetSegments(5,15); ``` - Obtain the animation duration or number of frames. > Note: The value **true** means to obtain the number of frames, and **false** means to obtain the duration (in ms). ``` animationItem.getDuration(); ``` - Add an event listener. > Note: For an event listener to be removed correctly, its callback function must be the same as that of the event listener already added and must be predefined. ``` AnimationEventName = 'enterFrame' | 'loopComplete' | 'complete' | 'segmentStart' | 'destroy' | 'DOMLoaded'; animationItem.addEventListener("enterFrame",function(){ // TODO something }) ``` - Change the animation color. > Note: The first parameter indicates the RGB color value. The second parameter indicates the animation layer and is optional. The third parameter indicates the subscript of the element corresponding to the animation layer and is optional. ``` animateItem.changeColor([255,150,203]) // Change the color of the entire animation. Or animateItem.changeColor([255,150,203],2) // Change the color of the second layer of the animation. Or animateItem.changeColor([255,150,203],2,2) // Change the color of the second element at the second layer of the animation. ``` - Remove an event listener. ``` animationItem.removeEventListener("enterFrame",function(){ // TODO something }) ``` - Resize the animation layout. ``` animationItem.resize() ``` - Set the animation fill mode. > Note: There are five fill modes: **Fill**, **Cover**, **Top**, **Bottom**, and **Container**. The default mode is **Contain**. ``` animateItem.setContentMode('Cover'); ``` - With lottie, you can destroy an animation in two modes: 1. **lottie.destroy**: destroys all animations; **lottie.destroy(name)** destroys the animation with the specified name. 2. **animateItem.destroy**: destroys a given animation. > Note: When there are multiple animations on one page and the animation instance is assigned to the same variable **animateItem**, only the last animation is destroyed when **animateItem.destroy** is called. Example: ``` this.animationItem = lottie.loadAnimation({ container: this.mainCanvasRenderingContext, // Rendering context renderer: 'canvas', // Rendering mode loop: true, // Whether the animation is repeated. The default value is true. autoplay: true, // Whether to enable automatic playback. The default value is true. name: 'cat', // Animation name contentMode: 'Contain', // Fill mode path: this.path, // JSON file path initialSegment: [10,50] // Initial segment of the animation }) this.animationItem = lottie.loadAnimation({ container: this.mainCanvasRenderingContext, // Rendering context renderer: 'canvas', // Rendering mode loop: true, // Whether the animation is repeated. The default value is true. autoplay: true, // Whether to enable automatic playback. The default value is true. name: '2016', // Animation name contentMode: 'Contain', // Fill mode path: this.path, // JSON file path initialSegment: [10,50] // Initial segment of the animation }) ``` In this example, calling **this.animationItem.destroy()** destroys only the animation whose name is **2016**, but not the one whose name is **cat**. When possible, use **lottie.destroy** to destroy an animation. ## Available APIs | Name | Type | Description | | --------------------- | ---------------------- | ------------------ | | play() | name? | Plays the animation. | | stop() | name? | Stops the animation. | | pause() | name? | Pauses the animation. | | togglePause() | name? | Switches the animation playback state between paused and running. | | destroy() | name? | Destroys the animation. | | goToAndStop() | value, isFrame?, name? | Seeks to a certain frame or point of time and stop the animation.| | goToAndPlay() | value, isFrame?, name? | Seeks to a certain frame or point of time and start the animation.| | setSegment() | init,end | Sets an animation segment. | | playSegments() | arr, forceFlag | Plays animation segments. | | resetSegments() | forceFlag | Resets the animation. | | setSpeed() | speed | Sets the playback speed. | | setDirection() | direction | Sets the playback direction. | | getDuration() | isFrames? | Obtains the animation duration. | | addEventListener() | eventName,callback | Adds an event listener. | | removeEventListener() | name,callback? | Removes an event listener. | | changeColor() | color, layer?, index? | Changes the animation color. | | setContentMode() | contentMode | Sets the fill mode. | ## New Features of the 2.0.0 Version 1. The animation color can be changed for canvas rendering. - The color value can be in RGB or RGBA format. - The color can be set for the start keyframe. 2. The masks/mattes features are supported for canvas rendering. - For masks, the supported modes are: mode = a, mode = s, mode = f. - For mattes, the supported modes are: tt = 1, tt = 2. 3. The Gaussian blur effect is added. 4. External resource images can be loaded for canvas rendering. - External resource images in the sandbox (which is searched before the **rawfile** folder) can be loaded. - External resource images in the **rawfile** folder can be loaded. 5. The fill mode can be set, with the following options available: - Fill (may be stretched, not cropped) - Top (aligned with the top edge, not cropped) - Bottom (aligned with the bottom edge, not cropped) - Cover (aligned with the bottom edge, may be cropped) - Contain (aligned with the top edge, may be cropped) ## Constraints lottie has been verified in the following versions: - DevEco Studio: NEXT Developer Beta1(5.0.3.122), SDK: API12(5.0.0.18) - DevEco Studio: 4.1 Canary(4.1.3.521), SDK: API11 (4.1.0.65) - DevEco Studio: 4.1 Canary(4.1.3.317), SDK: API11 (4.1.0.36) - DevEco Studio: 4.0 release(4.0.3.700), SDK: API10 (4.0.10.15) ## Directory Structure ```` /lottie # Root directory of the project ├── entry # Sample code ├── library # lottie library folder │ └─ src/main/js │ └─ build/player │ └─ lottie.js # Core code, including JSON parsing, animation drawing, and animation control │ └─index.d.ts # API declaration ├── README.md # Instructions for installation and usage ```` ## How to Contribute If you find any problem when using lottie, submit an [issue](https://gitee.com/openharmony-tpc/lottie/issues) or a [PR](https://gitee.com/openharmony-tpc/lottie/pulls) to us. ## License This project is licensed under the terms of the [MIT License](https://gitee.com/openharmony-tpc/lottie/blob/master/LICENSE). ## Features Not Yet Supported * HTML rendering mode * Filter effect in SVG rendering * Some masks and mattes features * Luminance mask (that is, tt = 3) * Rendering of onlineimage resources * Animation visibility control in components * Animation registration * Animation search * Animation data update * Certain effects * Animations containing expressions