-
animation 성능 향상 (requestAnimationFrame)기타 2023. 9. 4. 22:57
reflow, repaint로 인한 성능저하를 막기 위해서 GPU를 사용하여 애니메이션을 작업하는 것이 좋다.
GPU를 사용하는 편이 더 부드러운 애니메이션을 보여줄 수 있기 때문이다. (CPU보다 더 많은 core를 가지기에 단순 작업에 적합하다 / GPU의 하드웨어 가속 기능)
그 방법중 하나인 requestAnimationFrame 메서드에 대해서 알아보았다.
<!DOCTYPE html> <html> <head> <title>requestAnimationFrame 예제</title> <style> #canvas { background-color: #f0f0f0; } </style> </head> <body> <canvas id="canvas" width="400" height="400"></canvas> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var x = 200; // 원의 초기 x 위치 var y = 200; // 원의 초기 y 위치 var radius = 50; // 원의 반지름 var speed = 2; // 원의 이동 속도 function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // 캔버스를 지우기 ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI * 2, false); ctx.fillStyle = 'blue'; ctx.fill(); ctx.closePath(); // 캔버스 범위를 벗어나면 방향을 반대로 변경 if (x + radius > canvas.width || x - radius < 0) { speed = -speed; } // x 위치 업데이트 x += speed; requestAnimationFrame(draw); // 다음 프레임 요청 } draw(); // 애니메이션 시작 </script> </body> </html>원이 좌우로 이동하는 requestAnimationFrame 예제이다.
https://developer.mozilla.org/ko/docs/Web/API/window/requestAnimationFrame
Window: requestAnimationFrame() method - Web API | MDN
화면에 애니메이션을 업데이트할 준비가 될 때마다 이 메서드를 호출해야 합니다. 이는 브라우저가 다음 리페인트를 수행하기 전에 애니메이션 함수를 호출하도록 요청합니다. 콜백의 수는 보
developer.mozilla.org
'기타' 카테고리의 다른 글
Kotlin의 기초 문법 알아보기 (0) 2023.09.09 React 개발자가 공부해본 SwiftUI (1) 2023.09.07 Headless UI란? (0) 2023.09.03 선언적 프로그래밍이란? (0) 2023.08.30 SQL의 DDL, DML, DCL란? (0) 2023.08.25