在项目中,遇到需要在网页首屏,展示动画的需求,你会想到怎么做?
思路一:设计师导出gif图片,用img进行展示。
缺点:图片失真,影响效果。
思路二:设计师导出json文件,用插件解析成动画展示。
缺点:由于当时时间紧张,且不知道怎么操作,放弃了这个方案。
直到在下一个项目中,遇到需要自定义加载动画效果的需求,再次把该方案提上日程。在项目中,应该多去思考,凡事都有解决方案。
lottie-web 将json解析成动画。
一、安装依赖
npm install lottie-web --save
或者
yarn add lottie-web
二、在React项目中搭配Ant Desgin使用
注意:loading.json为设计师将动画设计好之后,导出的json文件。
import React, { useEffect, useRef } from 'react';
import lottie from 'lottie-web';
import { Spin } from 'antd';
import { SpinProps } from 'antd/lib/spin';
import loading from '@/assets/loading.json';
interface Props extends SpinProps {
children?: React.ReactNode;
}
const SIZE_MAP = {
small: 14,
default: 20,
large: 32,
};
const CustomLoad = (props: { style: React.CSSProperties }) => {
const load = useRef() as React.MutableRefObject<any>;
useEffect(() => {
lottie.loadAnimation({
container: load.current,
renderer: 'svg',
loop: true,
autoplay: true,
animationData: loading,
});
}, []);
return <div style={props.style} ref={load}></div>;
};
const CustomSpin = (props: Props) => {
const { children, size = 'default', ...rest } = props;
const style: React.CSSProperties = {
width: SIZE_MAP[size],
position: 'absolute',
top: '50%',
left: '50%',
marginTop: -SIZE_MAP[size],
marginLeft: -SIZE_MAP[size] / 2,
};
return (
<Spin {...rest} indicator={<CustomLoad style={style} />}>
{children}
</Spin>
);
};
export default CustomSpin;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)