如何使用React-Lottie将动画添加到React应用

news/2024/7/7 5:08:31

介绍 (Introduction)

Adobe After Effects can be an intuitive way to generate web animations, but there has historically been problems converting these animations to web apps. It is usually necessary to use a third party program to import an animation from After Effects.

Adobe After Effects可以是一种生成Web动画的直观方法,但是历史上一直存在将这些动画转换为Web应用程序的问题。 通常需要使用第三方程序从After Effects中导入动画。

One such program is Lottie, a program developed by Airbnb Design that allows you to use these animations in real time in a lightweight and flexible format. Lottie takes JSON data from an After Effects extension called Bodymovin and turns it into a usable animation for the web.

其中一个程序就是Lottie ,这是由Airbnb Design开发的程序,它允许您以轻巧灵活的格式实时使用这些动画。 Lottie从名为Bodymovin的After Effects扩展中获取JSON数据,并将其转换为网络上可用的动画。

In this article, we’ll be looking at how to use Lottie to add animations to our React applications. To do this, we’ll be using an npm package called react-lottie to generate viewable animations from JSON files exported by Bodymovin. Since we’ll be focusing on the app side of things, we won’t look into how these animations are created in After Effects, but rather use animations created and open sourced by designers on Lottiefiles. If you have animations on After effects that you would like to use, you can export them to JSON using the Bodymovin plugin for After Effects.

在本文中,我们将研究如何使用Lottie将动画添加到我们的React应用程序中。 为此,我们将使用一个名为react-lottie的npm包从Bodymovin导出的JSON文件生成可见的动画。 由于我们将重点放在应用程序方面,因此我们不会研究在After Effects中如何创建这些动画,而会使用设计师在Lottiefiles上创建和开源的动画。 如果您要使用After Effects上的动画,则可以使用After Effects的Bodymovin插件将其导出为JSON。

For this tutorial, we’ll build a React application that consists of two types of Lotties, one regular one and another with controlled animations depending on certain values in state.

在本教程中,我们将构建一个由两种类型的Lotties组成的React应用程序,一种是常规的,另一种是根据状态中的特定值具有受控动画的。

If you’d like to look at the finalized code, take a look at this CodeSandbox example.

如果您想看一下最终代码,请看下面的CodeSandbox示例 。

第1步-创建我们的应用程序 (Step 1 — Creating Our Application)

We’ll be using create-react-app to create our app. If you don’t have it installed yet, run the following command to do so:

我们将使用create-react-app来创建我们的应用程序。 如果尚未安装,请运行以下命令进行安装:

  • npm install --g create-react-app

    npm install --g创建React应用

Now let’s create our application:

现在创建应用程序:

  • create-react-app lottie-demo

    创建React应用程序抽签演示

This will create some boilerplate code for our app and configure our React development environment. Open up the lottie-demo directory and let’s get coding. Yarn is create-react-app’s default package manager, and it’s what we’ll use to handle our dependencies.

这将为我们的应用程序创建一些样板代码,并配置我们的React开发环境。 打开lottie-demo目录,让我们开始编码。 Yarn是create-react-app的默认程序包管理器,它是我们用来处理依赖项的工具。

Now let’s install our one and only dependency, react-lottie. To do this run this command in the terminal:

现在,让我们安装我们唯一的依赖关系react-lottie 。 为此,请在终端中运行以下命令:

  • yarn add react-lottie

    纱线添加React纱

Now let’s add our animations.

现在,让我们添加动画。

第2步-获取样本批次 (Step 2 — Getting our Sample Lotties)

We’ll be getting our sample animations from LottieFiles, so head over there and create a free account.

我们将从LottieFiles获取示例动画,因此请转到那里并创建一个免费帐户。

LottieFiles gives you access to a curated library of animations from designers all over the globe. It also provides a platform to test, upload, and share your own animations.

LottieFiles使您可以访问来自全球设计师的精选动画库。 它还提供了一个测试,上传和共享自己的动画的平台。

Browse through the animations, tweak the settings if necessary, and when you are happy with what you have click Download JSON to get the animation. Inside the src directory of our application, create two more directories, components and lotties. These will hold or React components and Lottie animation data respectively. Place the downloaded JSON files inside the lotties directory.

浏览动画,如有必要,调整设置,当您满意后,单击“ Download JSON以获取动画。 在我们应用程序的src目录中,再创建两个目录, componentslotties 。 这些将分别保存或React组件和Lottie动画数据。 将下载的JSON文件放在lotties目录中。

Now we are ready to create components that display these animations.

现在,我们准备创建显示这些动画的组件。

第3步-创建不受控制的彩票 (Step 3 — Creating Uncontrolled Lotties)

Animations can be allowed to run freely or be manipulated by data in state. First, let’s look at the first case and create an animation that imports and renders a lottie.

可以允许动画自由运行或由状态数据操纵。 首先,让我们看一下第一种情况,并创建一个导入并渲染抽签的动画。

Create a file called UncontrolledLottie.jsx inside the components directory and place the following code inside it:

components目录中创建一个名为UncontrolledLottie.jsx的文件,并将以下代码放入其中:

// UncontrolledLottie.jsx
import React, { Component } from 'react'
import Lottie from 'react-lottie'
import animationData from '../lotties/4203-take-a-selfie.json'

class UncontrolledLottie extends Component {


  render(){

    const defaultOptions = {
      loop: true,
      autoplay: true, 
      animationData: animationData,
      rendererSettings: {
        preserveAspectRatio: 'xMidYMid slice'
      }
    };

    return(
      <div>
        <h1>Lottie</h1>
        <p>Base animation free from external manipulation</p>
        <Lottie options={defaultOptions}
              height={400}
              width={400}
        />
      </div>
    )
  }
}

export default UncontrolledLottie

In this case, 4204-take-a-selfie.json is the JSON file of the lottie downloaded. Feel free to replace that with whichever you had downloaded.

在这种情况下, 4204-take-a-selfie.json是下载的彩票的JSON文件。 随时用您下载的内容替换。

Now let’s go through the information provided in the configuration. You will notice we pass an options prop to the Lottie component; this contains the configuration data for the animation to be rendered. This consists of:

现在,让我们浏览配置中提供的信息。 您会注意到我们将options道具传递给Lottie组件; 其中包含要渲染的动画的配置数据。 这包括:

  • animationData - an Object with the exported animation data, in our case, the json file

    animationData一个带有导出的动画数据的对象,在本例中为json文件

  • autoplay - a boolean determining if it will start playing as soon as it is ready

    autoplay -一个布尔值,确定一旦准备好是否会开始播放

  • loop - a boolean or number that determines if the animation will repeat or how many times it should repeat

    loop一个布尔值或数字,确定动画是否重复或应该重复多少次

  • rendererSettings - configuration data for the renderer

    rendererSettings配置数据

These are just some of the options you can provide.

这些只是您可以提供的一些选项。

We also provide the dimensions (length and width) of our animation as props to Lottie.

我们还提供了动画的尺寸(长度和宽度)作为Lottie道具。

This animation is now ready for use by importing it into our App.js. This will look like the following:

现在可以通过将其导入到App.js来使用该动画。 如下所示:

But first let’s add our controlled Lottie.

但是首先让我们添加受控的Lottie。

第4步-创建受控彩票 (Step 4 — Creating Controlled Lotties)

Lotties can be manipulated in React to change some of their properties using data in state. In our case, we’ll look at how we can play, stop, and pause the animations in our lottie.

可以在React中操纵Lotty以使用状态数据来更改其某些属性。 在本例中,我们将研究如何播放,停止和暂停乐透中的动画。

Let’s create a file in components and name it ControlledLottie.jsx. Place the following code in that file:

让我们在components创建一个文件,并将其命名为ControlledLottie.jsx 。 将以下代码放在该文件中:

// ControlledLottie.jsx
import React, { Component } from 'react'
import Lottie from 'react-lottie'
import animationData from '../lotties/77-im-thirsty.json'

class ControlledLottie extends Component {
  state = {isStopped: false, isPaused: false}

  render(){
    const buttonStyle = {
      display: 'inline-block',
      margin: '10px auto',
      marginRight: '10px',
      border: 'none',
      color: 'white',
      backgroundColor: '#647DFF',
      borderRadius: '2px',
      fontSize: '15px'

    };

    const defaultOptions = {
      loop: true,
      autoplay: true, 
      animationData: animationData,
      rendererSettings: {
        preserveAspectRatio: 'xMidYMid slice'
      }
    };

    return(
      <div className="controlled">
        <h1>Controlled Lottie</h1>
        <p>Uses state manipulation to start, stop and pause animations</p>
        <Lottie options={defaultOptions}
              height={400}
              width={400}
              isStopped={this.state.isStopped}
              isPaused={this.state.isPaused}
        />
        <button style={buttonStyle} onClick={() => this.setState({isStopped: true})}>Stop</button>
        <button style={buttonStyle} onClick={() => this.setState({isStopped: false, isPaused: false })}>Play</button>
        <button style={buttonStyle} onClick={() => this.setState({isPaused: !this.state.isPaused})}>Pause</button>
      </div>
    )
  }
}

export default ControlledLottie

Let’s analyze this code. There are a few key differences between this and ControlledLottie.jsx. We’ve added three buttons at the bottom along with their styling. These buttons are used to toggle the values of the data in state.

让我们分析一下这段代码。 此代码与ControlledLottie.jsx之间有一些关键区别。 我们在底部添加了三个按钮及其样式。 这些按钮用于切换状态中的数据值。

The Lottie component also has two more props:

Lottie组件还具有另外两个道具:

  • isStopped - a boolean indicating whether the animation is active or not

    isStopped一个布尔值,指示动画是否处于活动状态

  • isPaused - a boolean that indicates if the animation is paused or not

    isPaused一个布尔值,指示动画是否已暂停

Here’s what our controlled lottie component will look like:

这是我们受控彩票组件的外观:

Both our animations are ready to use now, so let’s import them into App.js and display them in our app.

我们的两个动画现在都可以使用,因此让我们将它们导入App.js并将其显示在我们的应用中。

Edit the code in App.js , importing our components and adding them inside the render function:

编辑App.js的代码,导入我们的组件并将其添加到render函数中:

// App.js
import React, { Component } from 'react';
import './App.css';
import UncontrolledLottie from './components/UncontrolledLottie';
import ControlledLottie from './components/ControlledLottie';

class App extends Component {
  render() {
    return (
      <div className="App">
        <h1>REACT LOTTIES</h1>
        <div className="lotties">
          <UncontrolledLottie />
          <ControlledLottie />
        </div>
      </div>
    );
  }
}

export default App;

Let’s style our app to make it mobile responsive. We can do this using CSS grid. Add the following code to your App.css file.

让我们对应用程序进行样式设置,使其具有移动响应能力。 我们可以使用CSS网格来做到这一点。 将以下代码添加到您的App.css文件中。

.lotties{
  display: grid;
  grid-template-columns: auto auto;
}

@media only screen and (min-device-width : 320px) and (max-device-width: 480px){
  .lotties{
    display: grid;
    grid-template-columns: auto;
  }
}

This places our lotties in two columns that will be reduced to a single column on devices with a smaller width.

这会将我们的彩票分为两列,在宽度较小的设备上将减少为一列。

Now fire up the application:

现在启动应用程序:

  • yarn start

    纱线开始

Your browser will open up and you will be able to see the two animations active. Clicking Pause will have the controlled animation freeze in its current frame. Clicking it again will resume it as well as clicking Play. Clicking Stop returns the animation to its default position and holds it there.

您的浏览器将打开,您将能够看到两个动画。 单击Pause将使受控动画冻结在其当前帧中。 再次单击它将恢复它并单击“ Play 。 单击“ Stop可使动画返回其默认位置并保持在该位置。

结论 (Conclusion)

Lottie can be used as a lightweight method to add animations to your web app. It can be used to make applications more interactive and provide visually appealing feedback, like animations indicating the state of certain processes. Lotties are performant, and will not put a heavy load on your application.

Lottie可以用作将动画添加到Web应用程序的轻量级方法。 它可用于使应用程序更具交互性,并提供视觉上吸引人的反馈,例如指示某些进程状态的动画。 抽签是高性能的,不会给您的应用程序带来沉重的负担。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-add-animations-to-react-apps-with-react-lottie


http://www.niftyadmin.cn/n/3649397.html

相关文章

Android系统常用隐藏命令大全

本文出自&#xff1a;http://androidkaifa.com/thread-1038-1-1.html android手机隐藏命令大全&#xff0c;用之前要考虑清楚尤其是涉及到格式化或者恢复出厂设置类的&#xff01; 注意&#xff1a;因Android版本较多&#xff0c;固有部分隐藏命令或不能使用&#xff08;笔者用…

WordPress文本工具实现代码执行功能

WordPress自带有两个小工具可以执行代码功能。一个是自定义HTML小工具&#xff0c;不过只能运行HTML、CSS、JavaScript三种语言。文本小工具默认是不可以运行代码的。要实现这个功能&#xff0c;需要添加以下代码。 使用方法&#xff1a;在当前主题目录下面的functions.php里面…

[LCS]启用WindowsMessenger5.0的调试日志功能来诊断登录LCS服务器

编写者&#xff1a;郑昀UltraPower摘要&#xff1a;Windows Messenger 5.0有一个注册表项设置&#xff0c;可以用来启用日志文件&#xff0c;该文件中记录了Windows Messenger 5.0登录LCS Server的详细来往包&#xff0c;可从其中得到通讯细节&#xff0c;从而作troubleshootin…

解决GridView与scrollview嵌套时GridView显示一行数据

重写GridView的onMeasure的方法: public class MyGridView extends GridView { public MyGridView(Context context, AttributeSet attrs) { super(context, attrs); } public MyGridView(Context context) { super(context); } public MyGridView(Context context, Attri…

如何通过npm和package.json使用Node.js模块

The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program. 作者选择了“ 开放互联网/言论自由基金会”作为“ Write for DOnations”计划的一部分来接受捐赠。 介绍 (Introduction) Because of such featu…

Android系统获取手机型号和系统版本号,以及其他配置信息

<pre name"code" class"java">String sdkandroid.os.Build.VERSION.SDK; // SDK号 String modelandroid.os.Build.MODEL; // 手机型号 String releaseandroid.os.Build.VERSION.RELEASE; // android系统版本号执行以下代码前&#xff0c;须在manifes…

网页模块实现电脑端显示(隐藏)手机端隐藏(显示)

在开发的很多时候&#xff0c;遇到有些模块在电脑端显示正常&#xff0c;而到手机端就显示不正常&#xff0c;或者有些模块只想在电脑或手机一端显示。另一端不显示。这个就要用到HTMLCSS的隐藏功能了。 1、电脑端显示&#xff0c;手机端隐藏&#xff0c;以下是CSS样式&#xf…

赵勖予:再见,CodeArtist(下)

Lee感到穷途末路。根据国家信息产业部当年的统计数字&#xff0c;我国IT行业的人才需求每年增加一百万&#xff0c;而这一百万中竟然没有单片机天才Lee的一个位置。激愤之下他甚至打算回安阳钢厂&#xff0c;再去做他的弱电工人&#xff0c;但世上又哪有如此好走的回头路&#…