-
TIL-2024.03.04 - 3js - Resizing & Animation> Frontend/ThreeJS 2024. 3. 4. 22:15
------ Resizing
Resizing 필요 이유:
창크기가 변경될때 Renderer가 변경되지 않아서, resizeEvent로 renderer의 사이즈 변경
const handleResize = () => { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); // 카메라 변경 후, 결과가 정상적으로 반영 renderer.setSize(window.innerWidth, window.innerHeight); renderer.render(scene, camera); // 새롭게 render 된 내용을 반영 }; window.addEventListener("resize", handleResize);
------ Animation
const render = () => { // 순서 // 1. requestAnimationFrame로 매 프레임 호출 // 2. 각기 호출되는 Frame 마다 3D Object에 변화를 줘서, 애니메이션 효과 발생 // 애니메이션 효과 적용 // cube.rotation.x = Date.now() / 1000; // 방법1. cube의 x 위치 JS Date.now로 변경 // cube.rotation.x = clock.getElapsedTime(); // 방법2. cube의 x 위치 ThreeJS Clock로 변경 cube.rotation.x += clock.getDelta(); // 방법3. cube의 x 위치를 Frame 간격에 따라 회전 각도 조절 cube.position.y = Math.sin(cube.rotation.x); // cube의 y 위치를 사인 함수를 통해 애니메이션 적용 cube.scale.z = Math.cos(cube.rotation.x); // cube의 z 스케일을 코사인 함수를 통해 애니메이션 적용 // Three.js Renderer를 사용하여 장면(scene)을 렌더링 // 이 때, 현재 카메라(camera)로 렌더링. renderer.render(scene, camera); // 프레임 호출 // 다음 프레임에서 render 함수를 호출하도록 requestAnimationFrame으로 설정 > 애니메이션 연속 실행 requestAnimationFrame(render); // 매 프레임마다 호출 }; // render 함수 호출하여 애니메이션 시작 render();
requestAnimationFrame란?
- requestAnimationFrame은 웹 애니메이션을 위한 브라우저 API.
- 브라우저는 애니메이션을 위해 다음 리페인트가 발생하기 직전에 지정된 함수를 호출
- 브라우저가 최적화된 타이밍에 애니메이션을 업데이트 가능.
- requestAnimationFrame은 브라우저에게 다음 프레임이 그려지기 직전에 실행할 콜백 함수를 제공하는 메서드입니다.
- 브라우저의 주기에 맞추어 애니메이션을 부드럽게 실행 (사용자의 장치와 성능에 맞게 애니메이션을 제공 > 성능에 따라 상이)
- 결과적으로, 애니메이션 루프에서 requestAnimationFrame을 사용하여 반복적으로 호출하여 애니메이션을 구현.
'> Frontend > ThreeJS' 카테고리의 다른 글
TIL-2024.03.11 - 3js - Fonts - 2 (0) 2024.03.11 TIL-2024.03.06 - 3js - Fonts - 1. 3D 폰트 만들기 (1) 2024.03.07 TIL-2024.03.03 - 3js - Light (0) 2024.03.03 TIL-2024.03.02 - 3js - 기초 Scene, Camera, renderer (0) 2024.03.02 TIL-2024.03.01 - Three.JS 기초 (0) 2024.03.01