[javascript] 자바스크립트에서 애니메이션(Animation) 구현 방법

웹 개발에서 애니메이션은 사용자 경험을 향상시키고 사용자와의 상호작용을 높이는 데 큰 역할을 합니다. 자바스크립트를 사용하여 애니메이션을 구현하는 방법에 대해 알아보겠습니다.

1. CSS 애니메이션 활용

CSS를 사용하여 간단한 애니메이션을 만들 수 있으며, 자바스크립트를 사용하여 CSS 클래스를 추가/제거하여 애니메이션을 트리거할 수도 있습니다.

<div id="box" class="animate"></div>
<button onclick="toggleAnimation()">애니메이션 토글</button>

<style>
  .animate {
    width: 100px;
    height: 100px;
    background-color: red;
    transition: width 2s, height 2s, background-color 2s, transform 2s;
  }

  .animate.animate-active {
    width: 200px;
    height: 200px;
    background-color: blue;
    transform: rotate(180deg);
  }
</style>

<script>
  function toggleAnimation() {
    var element = document.getElementById('box');
    element.classList.toggle('animate-active');
  }
</script>

2. 자바스크립트 애니메이션 라이브러리 활용

더 복잡한 애니메이션을 만들기 위해 자바스크립트 애니메이션 라이브러리를 활용할 수도 있습니다. GreenSock(TweenMax), Velocity.js, Anime.js 등이 널리 사용되는 라이브러리입니다.

<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script>
  <style>
    #box {
      width: 100px;
      height: 100px;
      background-color: red;
    }
  </style>
</head>
<body>
  <div id="box"></div>
  <script>
    gsap.to("#box", { duration: 2, x: 200, rotation: 360 });
  </script>
</body>
</html>

3. requestAnimationFrame() 활용

requestAnimationFrame() 메서드를 사용하면 브라우저의 다음 리페인트 이전에 애니메이션을 업데이트할 수 있습니다. 이를 이용하여 고성능 애니메이션을 만들 수 있습니다.

var element = document.getElementById('box');
var position = 0;

function animate() {
  position += 1;
  element.style.left = position + 'px';
  if (position < 200) {
    requestAnimationFrame(animate);
  }
}

requestAnimationFrame(animate);

자바스크립트를 활용하여 다양한 방법으로 애니메이션을 구현할 수 있습니다. 선택한 방법에 따라 성능, 유지보수성, 제어 가능성 등을 고려하여 적절한 방법을 선택할 수 있습니다.

참고 자료: