前端加载lottie json动画效果
数据格式
//lottie json关键字段解释
lottie.json关键字
ip:起始帧
op:结束帧
w:宽
h:高
v:版本
fr:频率/帧率
ddd
nm
tiny
fonts:字体
list
fontConfig
asset:资源
assetConfig
id
w:宽
h:高
u:路径
p:名称
e
layers:图层
layerConfig
st:开始帧
ip:起始帧
op:结束帧
nm:名字
ind:图层id
ty:图层类型
ks:动画
shapes:图形
使用
需要专有组件库,官方版实测出现问题,因此选择第三方库,地址:www.npmjs.com/package/lot…
安装
yarn add lottie-react
//or
npm i lottie-react
使用
import React from "react";
import Lottie from "lottie-react";
import groovyWalkAnimation from "./groovyWalk.json";
const App = () => <Lottie animationData={groovyWalkAnimation} loop={true} />;
export default App;
hooks(实测失败)
import React from "react";
import { useLottie } from "lottie-react";
import groovyWalkAnimation from "./groovyWalk.json";
const App = () => {
const options = {
animationData: groovyWalkAnimation,
loop: true
};
const { View } = useLottie(options);
return <>{View}</>;
};
export default App;
自带api
实例
"react": "^17.0.2",
"lottie-react": "^2.3.1",
import Lottie from "lottie-react";
import { useQuery } from "react-query";
import styles from "./index.module.scss";
const Test:React.FC=()=>{
const {isLoading,data}=useQuery(["animation:miniword"],async()=>{
const res=await fetch("animation/loopball.json")
return res.json()
})
return (
<div className={styles.test}>
{isLoading ? "加载中" : <Lottie animationData={data} />}
</div>
)
}
export default Test;
注意
可能出现react-runtime类型错误
解决方式
全局类型文件中增加
declare module "react/jsx-runtime" { export default any; }