使用vue3结合requestAnimationFrame计算网页的帧数FPS

每跑完一次requestAnimationFrame,就说明跑完一帧了,所以我们只需要计算出:一秒内跑了多少次 requestAnimationFrame即可

import { Ref, ref } from 'vue';

export interface UseFpsOptions {
	every?: number;
}

export const useFps = (options?: UseFpsOptions): Ref => {
	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;
};

使用vue3结合requestAnimationFrame计算网页的帧数FPS_第1张图片

你可能感兴趣的:(javascript,前端,vue.js)