每跑完一次requestAnimationFrame
,就说明跑完一帧了,所以我们只需要计算出:一秒内跑了多少次 requestAnimationFrame即可
import { Ref, ref } from 'vue';
export interface UseFpsOptions {
every?: number;
}
export const useFps = (options?: UseFpsOptions): Ref<number> => {
const fps = ref(0);
const every = options?.every ?? 10;
//记录起始时间
let last = performance.now();
let ticks = 0;
const update = () => {
ticks += 1;
//间隔到了再重新计算
if (ticks >= every) {
const now = performance.now();
//计算出这一帧用了多久
const diff = now - last;
//用1000ms 去除以 一帧用的ms 可以得出帧数
fps.value = Math.round(1000 / (diff / ticks));
last = now;
ticks = 0;
}
//一直跑 requestAnimationFrame(update);
requestAnimationFrame(update);
};
requestAnimationFrame(update);
return fps;
};