uniapp实现数字自增长动画
时间: 2023-09-09 18:07:25 浏览: 56
在uniapp中实现数字自增长动画,可以使用 `requestAnimationFrame` 方法和 `setInterval` 方法结合实现。
以下是一个示例代码:
```
<template>
<view>
<text>{{ num }}</text>
</view>
</template>
<script>
export default {
data() {
return {
num: 0,
finalNum: 100,
interval: null,
startTime: null,
duration: 1000, // 动画持续时间,单位ms
};
},
mounted() {
this.initAnimation();
},
methods: {
initAnimation() {
this.startTime = null;
this.interval = setInterval(() => {
if (!this.startTime) {
this.startTime = Date.now();
}
const elapsed = Date.now() - this.startTime;
if (elapsed >= this.duration) {
clearInterval(this.interval);
this.num = this.finalNum;
} else {
const progress = elapsed / this.duration;
const currentNum = Math.floor(this.finalNum * progress);
this.num = currentNum;
}
}, 16.7); // 60fps
},
},
};
</script>
```
在上面的代码中,我们使用 `setInterval` 方法来每隔一定时间更新 `num` 的值,从而实现数字的自增长动画效果。在更新 `num` 的值时,我们使用了 `requestAnimationFrame` 方法来实现更流畅的动画效果。
需要注意的是,为了避免动画执行过程中用户进行了其他操作导致动画失效,我们在 `initAnimation` 方法中使用了一个 `startTime` 变量来记录动画开始时间,并在每次更新 `num` 的值时计算出已经经过的时间,如果已经达到了动画持续时间,就停止更新 `num` 的值。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)