devSoyoung / STUDY

✏️ 공부한 내용 정리, 주제에 따라 분류
4 stars 1 forks source link

window.requestAnimationFrame #26

Open devSoyoung opened 4 years ago

devSoyoung commented 4 years ago

IE 낮은 버전에서 지원 안됨

window.requestAnimationFrame

window.cancleAnimationFrame


Reference

devSoyoung commented 4 years ago

requestAnimationFrame과 setTimeout 애니메이션 비교

// main.js
let requestId = 0;
let lpos = 0;
let targetEl = document.querySelector('#animated');

function render() {
  targetEl.style.left = `${(lpos += 3) % 600}px`;
  requestId = window.requestAnimationFrame(render);
  // requestId = setTimeout(render, 1000 / 60);
}

function start() {
  requestId = window.requestAnimationFrame(render);
  // requestId = setTimeout(render, 1000 / 60);
}

function stop() {
  if (requestId) {
    window.cancelAnimationFrame(requestId);
    // clearInterval(requestId);
  }
}

requestAnimationFrame이 창 크기를 변경할 때 보다 깔끔한 애니메이션을 구현해줌

예제 실행을 위한 HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    div {
      position: absolute;
      left: 10px;
      top: 100px;
      padding: 50px;
      background: yellowgreen;
      color: white;
    }
  </style>
</head>

<body>
  <div id="animated"></div>
  <button onClick="start()">Start</button>
  <button onClick="stop()">Stop</button>
  <script src="main.js"></script>
</body>

</html>