목차

Javascript HTML DOM Animation

  • description : Javascript HTML DOM Animation
  • author : 오션
  • email : shlim@repia.com
  • lastupdate : 2021-04-20


Source of the article


JavaScript를 사용하여 HTML 애니메이션 제작 방법을 학습합니다.

A Basic Web Page

JavaScript로 HTML 애니메이션을 만드는 방법을 보여주기 위해, 간단한 웹 페이지를 사용합니다.

예제

<!DOCTYPE html>
<html>
<body>
 
<h1>My First javaScript Animation</h1>
 
<div id="aninamtion">My animation will go here</div>
 
</body>
</html>

Create an Animation Container

FIXME모든 애니메이션은 컨테이너 요소에 상대적(relative)이어야 합니다.

예제

<div id ="container">
  <div id ="animate">My animation will go here</div>
</div>

Style the Elements

컨테이너 요소는 style = “position: relative”로 생성되어야 합니다.

애니메이션 요소는 style = “position: absolute”로 생성되어야 합니다.

예제

<style>
  #container {
    width: 400px;
    height: 400px;
    position: relative;
    background: yellow;
  }
 
  #animate {
    width: 50px;
    height: 50px;
    position: absolute;
    background: red;
  }
</style>

Animation code

JavaScript 애니메이션은 요소 스타일의 점진적인 변경을 프로그래밍 하여 수행됩니다.

변경 사항은 타이머에 의해 호출됩니다. 타이머 간격이 작으면 애니메이션이 연속적으로 보입니다.

기본 코드는 다음과 같습니다.

예제

var id = setInterval(frame, 5);
 
function frame() {
  if(/* test for finished */) {
    clearInterval(id);
  } else {
    /* code to change the element style */
  }
}

Create the Full Animation Using JavaScript

예제

  <script>
    var id = null;
    function myMove() {
      var elem = document.getElementById("animate");
      var pos = 0;
      clearInterval(id);
      id = setInterval(frame, 5);
      function frame() {
        if (pos == 350) {
          clearInterval(id);
        } else {
          pos++;
          elem.style.top = pos + "px";
          elem.style.left = pos + "px";
        }
      }
    }
  </script>