삼각 함수
사인, 코사인, 탄젠트 등 삼각 함수 계산을 하거나 캔버스와 SVG에서 애니메이션 효과를 줄 때 자주 사용됩니다.
구문
Math.PI: 원주율Math.cos(값): 코사인(cos)Math.sin(값): 사인(sin)Math.tan(값): 단젠트(tan)Math.acos(값): 코사인 역함수(acos)Math.asin(값): 사인 역함수(asin)Math.atan(값): 탄젠트 역함수(atan)Math.atan2(y, x): (x, y)좌표가 이루는 각도
예시
Math.PI; // 3.141592653589793
Math.cos((90 * Math.PI) / 180); // cos 90° 6.123233995736766e-17*
Math.sin((90 * Math.PI) / 180); // sin 90°1
Math.tan((45 * Math.PI) / 180); // tan 45° 0.9999999999999999*
Math.acos(1); // 역힘수 사인 1 = 0
(Math.atan2(1, 1) * 180) / Math.PI; // (1, 1)의 좌표가 이루는 각도 45도
삼각함수로 원을 그리는 애니메이션 만들기
반지름이 100인 원주에 degree 위치 좌표는 다음과 같습니다.
// 각도
let degree = 0
// 회전각을 라디안으로 구하기
const rotation = (degree * Math.PI) / 100;
// 회전각으로 위치 구하기
const targetX = 100 * Math.cos(rotation);
const targetY = 100 * Math.sin(rotation);
degree를 일정 주기로 1도씩 증가시키면 원을 그리는 애니메이션을 구현할 수 있습니다.
- html
- javascript
- JSX
<div class="character"></div>
// 캐릭터 이미지
const character = document.querySelector('.character');
// 각도
let degree = 0;
// 루프 시작
loop();
// 화면이 갱신될 때마다 실행되는 함수
function loop() {
// 회전각을 라디안으로 구하기
const rotation = (degree * Math.PI) / 100;
// 회전각으로 위치 구하기
const targetX = window.innerWidth / 2 + 100 * Math.cos(rotation) - 50;
const targetY = window.innerHeight / 2 + 100 * Math.sin(rotation) - 50;
// character 위치 반영하기
character.style.left = `${targetX}px`;
character.style.top = `${targetY}px`;
// 각도 1도 증가
degree += 1;
// 다음 화면 갱신 타이밍에서 loop() 실행
requestAnimationFrame(loop);
}
라이브 에디터
function CircularAnimation() { const [position, setPosition] = useState({ x: 0, y: 0 }); const wrapRef = useRef(null); useEffect(() => { let degree = 0; let requestID; const loop = () => { const rotation = (degree * Math.PI) / 100; if (wrapRef.current) { const { clientWidth, clientHeight } = wrapRef.current const targetX = clientWidth / 2 + 60 * Math.cos(rotation) - 30; const targetY = clientHeight / 2 + 60 * Math.sin(rotation) - 30; // 상태 업데이트 -> 컴포넌트 리렌더링 발생 setPosition({ x: targetX, y: targetY }); } degree += 1; requestID = requestAnimationFrame(loop); }; requestID = requestAnimationFrame(loop); return () => { if (requestID) cancelAnimationFrame(requestID); } }, []); return ( <div ref={wrapRef} style={{ position: 'relative', width: '100%', height: 180 }}> <div style={{ position: 'absolute', top: 0, left: 0, width: 60, height: 60, borderRadius: '50%', background: 'dodgerblue', transform: `translate(${position.x}px, ${position.y}px)`, }} /> </div> ); }
결과
Loading...