前端使用lottie的json动画在单文件h5(非模块化)

725 阅读1分钟

步骤1.引入文件cdn

<script type="text/javascript" src="./script/data.json"></script>   //我的地址仅供参考
<!--引入lottie的js文件地址-->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.9.1/lottie.min.js"></script>

步骤2. ajax引入json文件,json文件如下图所示,这是ui设计提供,我完全不用处理的

image.png 步骤3.miss

步骤4.html显示,这样写 简简单单,

<div id="lottie"></div>

image.png

步骤5.css样式这样写

 #lottie {
        background-color: #fff;
        width: 100%;
        height: 100%;
        display: block;
        transform: translate3d(0, 0, 0);
        text-align: center;
        opacity: 1;

    }
    

步骤6:初始化播放方法,在mounted生命周期里面调用,jquery的ajax获取json,方法生成,导入数据到本页面中来,定时器settimeout 处理暂停动画播放

  getLotty() {
                $.ajax({
                    url: "./script/data.json",
                    type: 'GET',
                    data: '',
                    success: (res) => {
                        // this.animationData = res
                        let params = {
                            container: document.getElementById('lottie'),
                            renderer: 'svg',
                            loop: false,
                            autoplay: true,
                            animationData: res
                        };
                        this.anim = lottie.loadAnimation(params);
                        this.isshowFirst_start_button=true
                        // 开一点头,设置跳到指定帧数然后暂停
                        this.anim.goToAndStop(20,false)
                        var timer_SET = setTimeout(() => {
                            if(timer_SET){clearTimeout(timer_SET)}
                            // this.isShowContinue_button =true
                            this.isShowContinue_button_two =true
                            this.anim.pause()
                           this.isshowFirst_start_button=false
                            //   动画暂停的时间是不是需要调整
                        }, 30000);
                        this.anim.addEventListener('complete', () => {
                            //  加载第二个动画
                            this.initTwo_animation()
                        });

                    }
                });
            },

步骤7.有个小坑,如果是循环播放情况下,complete 回调函数不会触发的,下面这个loopcomplete才会触发

     this.animValueTwo.addEventListener('loopComplete', () => {
                            //  显示最后的按钮 
                            // this.isShowXinYuan=true
                        });