实现数字快速变化的动画效果(gsap)

一、gsap实现

1. 安装且引入gsap

npm install gsap

import gsap from "gsap"

2. 页面中添加计步器用来改变数值(也可以用按钮),添加h2用来展示数字改变的动画效果

   <div>

        <input type="number" step="100" v-model="counter">

        <h2>当前计数:{{ showNumber.toFixed(0) }}</h2>

    </div>

3. 在data里定义两个数值

   data() {

        return {

            counter: 0, // 初始

            showNumber: 0, // 承接

        }

    },

4. 在watch里面监听要改变的原始数值

   watch: {

        counter(newValue, oldValue) {

            gsap.to(this, { duration: 0.5, showNumber: newValue })

        }

    },

二、Vue动画实现

tip:建议使用gsap。

1. 页面中添加计步器用来改变数值(也可以用按钮),添加h2用来展示数字改变的动画效果

2. 在data里定义三个数值

3. 在watch里面监听要改变的原始数值并添加动画

   watch: {

        counter(newValue, oldValue) {

            let startTime = null;

            const animate = (timestamp) => {

                console.log("timestamp", timestamp);

                if (!startTime) startTime = timestamp;

                const progress = timestamp - startTime;

                // 根据动画进度计算数字的变化值

                this.showNumber = Math.floor(oldValue + (progress / this.animationDuration * 100));

                if (progress < this.animationDuration) {

                    // 继续执行动画

                    requestAnimationFrame(animate);

                }

            };

            // 开始执行动画

            requestAnimationFrame(animate);

        }

    },

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容