javascript - 速度控制一个 requestAnimationFrame 循环
问题描述
我有一个方法method2
循环遍历一些数字,直到它到达末尾然后它重置。但是我需要控制它的速度。在另一种方法 ( method1
) 中,我通过鼠标移动遍历这些数字,我使用以下方法控制此速度:
this.speedController += 1;
if (this.speedController < this.speed) {
return;
}
if (this.speedController > this.speed) {
this.speedController = 0;
}
我怎么能在我method2
的 .
method2
:
spin(index) {
let i = index;
if (i >= this.images.length) {
i = 1;
}
this.current = i;
this.animationRequestID = window.requestAnimationFrame(() => this.spin(i));
i += 1
},
编辑:
只是尝试使用超时,但是在停止动画时,我必须清除超时并运行clearAnimationFrame
,这似乎是错误的。
spin(index) {
window.setTimeout(() => {
let i = index;
if (i >= this.images.length) {
i = 1;
}
this.current = i;
this.animationRequestID = window.requestAnimationFrame(() => this.spin(i));
i += 1
}, this.speed * 10)
},
解决方案
设法找到答案并使其适应我的需求,对于尝试此操作的其他任何人,请记住这是一个 Vue 组件。
export default {
data() {
return {
spinStart: null,
spinThen: Date.now(),
fps: 1000 / 5
};
},
created() {
if (this.animation) {
this.spinStart = this.spinThen;
this.spin(1);
}
},
methods: {
spin(index) {
let i = index;
if (i >= this.images.length) {
i = 1;
}
this.animationRequestID = window.requestAnimationFrame(() => this.spin(i));
let now = Date.now();
let elapsed = now - this.spinThen;
if (elapsed > this.fps) {
this.spinThen = now - (elapsed % this.fps);
this.current = i;
i += 1;
}
},
推荐阅读
- r - 如何在其他列的所有组合中改变新列?
- python - 字典中的“sum”和“first”如何与 DataFrame.Series 相关?
- php - PHP 存储 awk 结果以分解为更多解析
- javascript - 无法使用 Chrome 扩展程序设置 cookie
- python - 使蒙版边界在实例分割蒙版中更加明显
- python - 在 Python 中访问 SOAP XML 响应中的嵌套子项的问题
- r - 种子设置:为什么输入不变后输出不同
- kubernetes - Strimzi 的 Apache Kafka 运算符是否仍处于测试版?
- reactjs - 当 redux 状态发生变化时,React-Redux 在屏幕上渲染组件两次
- php - /dev/urandom 上的 Wordpress open_basedir 错误