Frontend/Three.js
초당 프레임 수(FPS) 체크하기
wam
2024. 8. 28. 02:20
// Three.js 기본 설정
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// FPS 체크를 위한 Stats 설정
const stats = new Stats();
document.body.appendChild(stats.dom);
// 간단한 큐브 생성
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
// 애니메이션 루프
function animate() {
requestAnimationFrame(animate);
// 큐브를 회전시킴
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
// 렌더링
renderer.render(scene, camera);
// Stats 업데이트
stats.update();
}
animate();
Stats.js: stats.js 라이브러리를 불러와 초당 프레임 수(FPS)를 체크하고 화면에 표시한다.
애니메이션 루프: requestAnimationFrame을 이용해 애니메이션 루프를 구현하며, 이 루프에서 stats.update()를 호출하여 FPS를 매 프레임마다 업데이트한다.
이 코드를 실행하면 화면의 왼쪽 상단에 FPS가 표시된다. Three.js로 렌더링 된 장면이 업데이트될 때마다 FPS가 업데이트된다.
- stats는 3JS 기능이 아닌 라이브러리이다.
- 프레임 수가 떨어진다면 애니메이션이 버벅인다는 뜻 (초당 60 프레임 적정)
- 테스트할 때 콘솔에 출력하는 것이 약간의 부하를 발생시킨다.
- 실제 성능하고 비슷하게 테스트할 때는 콘솔 출력 없이 stas 추가해서 확인하자