react+ts项目使用lottie-web

lottie 可转化为基于svg的可动可交互的图片一种json数据格式,可以为网站增色不少。

1.下载lottie 

LottieFiles: Download Free lightweight animations for website & apps.

Creattie - Premium Lottie Animations & Animated Icons

2.使用lottie 

(1)下载lottie-web插件

npm i lottie-web

(2)创建tsx组件

基础使用

一个返回按钮 

import Lottie,{AnimationItem} from 'lottie-web'
import {Component} from "react";
import * as Back from './json/back.json'
type PropT = NonNullable<unknown>
type StateT = {
    backL:AnimationItem|null;
}
export default class BackLottie extends Component<PropT,StateT> {
    constructor(props: PropT) {
        super(props as PropT)
        this.state = {
            backL:null
        }
    }
    componentDidMount() {
        const backL = Lottie.loadAnimation({
            // 获取dom
            container: document.getElementById('back-lottie') as Element,
            // 渲染方式
            renderer: 'svg',
            // 循环
            loop: true,
            // 自动播放
            autoplay: false,
            // lottie信息
            animationData:Back,
        })
        // 播放速度
        backL.setSpeed(2);
        // 播放完成暂停
        backL.addEventListener('loopComplete',()=>backL.pause())
        // 保存dom实例
        this.setState({
            backL
        })
    }
    backFN = () =>{
        this.state.backL!.play()
    }
    render() {
        return <div id="back-lottie" style={{width:'100%',height:'100%'}} onClick={this.backFN}/>
    }
}
切换使用

 一个菜单与关闭双状态按钮

import Lottie, {AnimationItem} from 'lottie-web'
import {Component} from "react";
// 引入lottie json文件
import * as Menu from './json/menu.json'
type PropsT = {
  handleClick:(arg0: boolean)=>void, 
  open:boolean    
}
type StateT = {
    menuL: AnimationItem|null,
}
export default class MenuLottie extends Component<PropsT,StateT>{
  constructor(props: PropsT) {
    super(props)
    this.state = {
      menuL:null,
    }
  }
  componentDidMount() {
   const menuL = Lottie.loadAnimation({
      //  展示lottie原生的dom
      container: document.getElementById('menu-lottie') as Element,
      // 渲染方式 
      renderer: 'svg',
      //  循环
      loop:false,
      //  是否自动播放 
      autoplay: false,
      //  lottie json文件 
      animationData:Menu,
    })
    menuL.setSpeed(3);
    this.setState({
      menuL
    })
  }
  openMenu = () =>{
      if(this.props.open){
          // 播放哪一部分片段 从下载的地方可以看到
          this.state.menuL!.playSegments([70,140],true);
      }else{
          this.state.menuL!.playSegments([0,70],true);
      }
      this.props.handleClick(!this.props.open)
  }
  render() {
      return <div id="menu-lottie" style={{width:'100%',height:'100%'}} onClick={this.openMenu}/>
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值