물결 이동 애니메이션
IT 2024. 1. 28. 00:21
js에서 requestAnimationFrame함수를 활용하여 물결처럼 나아가는 움직임을 구현해보았다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>Document</title>
<style>
body {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
#container {
position: relative;
width: 500px;
height: 500px;
background-color: black;
}
.ball {
position: absolute;
top: 0;
left: 0;
display: inline-block;
width: 50px;
height: 50px;
border-radius: 100%;
background-color: red;
}
</style>
</head>
<body>
<!-- 시간에 따라 공이 움직이는 효과 -->
<div id="container">
<div class="ball"></div>
</div>
<script type="module">
let rafId;
const ball = document.querySelector(".ball");
let xPos = 0;
let yPos = 250;
const xSpeed = 1;
const writeInnerHtml = (targetID, content) => {
document.getElementById(targetID).innerHTML = content;
};
const draw = (timestamp) => {
if (xPos >= 450) {
cancelAnimationFrame(rafId);
return;
}
xPos += xSpeed;
yPos = 250; // 중심축
// x훅 이동 방향에 대한 물결파 높이 계산
// 진폭, 주기롤 조절함
const amp = 123;
const per = 1200;
yPos += amp * Math.sin(per * xPos);
ball.style.left = xPos + "px";
ball.style.top = yPos + "px";
rafId = requestAnimationFrame(draw);
};
draw();
</script>
</body>
</html>
공의 움직임을 구현하기 위해, sin 함수를 사용하여 y축에 대한 공의 높이를 계산했으며, 진폭으로는 공이 진동하는 높이를, 주기로는 공이 움직이는 속도를 구현할 수 있었다.
그리고 자연스러운 움직임을 위해 requestAnimationFrame을 사용하여, 매 프레임마다 공의 위치를 계산하도록 했고, x축으로 450px이상 가면 애니메이션이 멈추도록 했다.
자연어 처리의 기술 (0) | 2025.03.14 |
---|---|
정책 (0) | 2024.07.20 |
장애인 차별 금지법에 따른 웹 접근성 (0) | 2024.02.07 |
참고 블로그 사이트 정리 (0) | 2024.01.15 |
서브 도메인 자동 생성 기능 (0) | 2023.07.09 |